Escreva um plugin jQuery que retorne valores
Estou escrevendo um plugin jQuery que armazena alguns dados em alguns casos.
Eu gostaria de escrevê-lo de uma maneira muito flexível, onde eu posso alterar um parâmetro de entrada para obter algum valor que foi armazenado pelo plugin.
Explicação:
Quando eu ligo$("#any").myPlugin()
, meu plugin inicializa a criação de umdiv
e algunsa
dentro. Clicando em uma
vai guardar.index()
usando o.data()
método. Se eu ligar$("#any").myPlugin("getSelection")
gostaria de obter o valor armazenado com.data()
.
O que eu tentei:
(function ($) {
$.fn.myPlugin = function (action) {
if (action == null) action = "initialize";
return this.each(function ($this) {
$this = $(this);
if (action == "initialize") {
$this.html('<div></div>');
var div = $("div", $this);
div.append('<a>A</a>').append('<a>B</a>').append('<a>C</a>');
div.children("a").each(function (i) {
$(this).click(function (event) {
// Here I store the index.
$this.data($(this).index());
event.preventDefault();
return false;
});
});
return $this;
} else if (action == "getSelection") {
// With this action, I tried to get the stored value.
return $this.data("selectedValue");
}
});
};
})(jQuery);
Chamada simples para criar os elementos:
$("#someElement").myPlugin();
E aqui eu tentei obter o índice, sem sucesso:
alert($("#someElement").myPlugin("getSelection"));
Então, é possível fazer o que estou tentando?