2010-06-15 15 views
6

Me gustaría crear un plugin de jQuery con un API de algo como esto:Creando un complemento de jQuery, ¿cómo hago ámbitos personalizados?

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

En lugar de éstos:

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

Básicamente, en lugar de tener que namespace cada método que actúa de forma similar a aquellas en las jQuery, me gustaría "alcance" los métodos a una API personalizada, donde $("#chart).pluginName() devolvería un objeto tal que get, attr, find, y algunos otros serían completamente reescritos.

Estoy seguro de que esta no es una idea popular ya que rompe con la convención (¿no?), Pero es más fácil y más legible, y probablemente más optimizada, que las dos opciones anteriores. ¿Cuáles son tus pensamientos?

Respuesta

2

Estoy experimentando con la idea.

Parece que podría modificar las funciones del objeto jQuery que recibe el complemento y devolverlo.

Algo como esto:

$.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/(actualizada del original a la sobrescribir .html() así)

$.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');​ 

EDIT:

Como alternativa, si va a almacenar en caché los elementos a los que se deben aplicar los métodos personalizados, puede .apply() los métodos antes de usarlos.

basarse en el ejemplo anterior:

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 

Cuestiones relacionadas