Pergunta

Eu gostaria de criar um plugin jQuery com uma API algo como isto:

$("#chart").pluginName().attr("my_attr");

Em vez de estes:

$("#chart").pluginName_attr("my_attr");
$.pluginName.attr("#chart", "my_attr");

Basicamente, em vez de ter de espaço de nomes de cada método que atos semelhantes àquelas em jQuery, gostaria de "escopo" os métodos para uma api personalizado, onde $("#chart).pluginName() gostaria de retornar um objeto, que get, attr, find, e alguns outros poderiam ser completamente reescrito.

Tenho certeza de que esta não é um bem-gostado idéia de como ele quebra convenção (não é?), mas é mais fácil e mais fácil de ler, e provavelmente mais otimizada, do que as duas opções acima.Quais são seus pensamentos?

Foi útil?

Solução

Eu estou experimentando com a idéia.

Parece que você apenas pode modificar as funções para o objeto jQuery que o plugin recebe, e retornar.

Algo como isto:

$.fn.tester = function() {  // The plugin

    this.css = function() {  // Modify the .css() method for this jQuery object
        console.log(this.selector);   // Now it just logs the selector
        return this;     // Return the modified object
    }
    return this;   // Return the modified object

}

http://jsfiddle.net/EzzQL/1/ (actualizado a partir do original para substituir .html() bem)

$.fn.tester = function() {
    this.css = function() {  
        console.log(this.selector);  // This one logs the selector
        return this;
    }
    this.html = function() {
        alert(this.selector); // This one alerts the selector
        return this;
    }
    return this;
};

// Because .css() and .html() are called after .tester(),
// they now adopt the new behavior, and still return a jQuery
//    object with the rest of the methods in tact
$('#test1').tester().css().html().animate({opacity:.3}); 


// .css() and .html() still behave normally for this one
//    that doesn't use the plugin
$('#test2').css('backgroundColor','blue').html('new value');​

EDITAR:

Como alternativa, se você estiver indo para colocar em cache os elementos para os quais os métodos personalizados devem ser aplicadas, você pode .apply() os métodos antes de usá-los.

Para inspirar-se no exemplo acima:

var $test1 = $('#test1');  // Cache the elements

$.fn.tester.apply($test1,[this]);  // apply() the new methods

$test1.css().html().animate({opacity:.3});  // Use the new methods

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top