Creazione di un plugin jQuery, Come posso fare personalizzati Scopes?
Domanda
vorrei creare un plugin jQuery con un qualcosa di API in questo modo:
$("#chart").pluginName().attr("my_attr");
Al posto di questi:
$("#chart").pluginName_attr("my_attr");
$.pluginName.attr("#chart", "my_attr");
In sostanza, invece di dover namespace ogni metodo che agisce simile a quelli di jQuery, mi piacerebbe "scope" i metodi per un'API personalizzata, dove $("#chart).pluginName()
restituirebbe un oggetto in modo tale che get
, attr
, find
, e pochi altri sarebbero completamente riscritti.
Sono sicuro che questo non è un'idea ben voluto in quanto rompe convenzione (lo fa?), Ma è più facile e più leggibile, e, probabilmente, più ottimizzato, rispetto alle due opzioni di cui sopra. Quali sono i tuoi pensieri?
Soluzione
sto sperimentando con l'idea.
Sembra che si può solo modificare le funzioni per l'oggetto jQuery che il plugin riceve, e restituire questo.
Qualcosa di simile a questo:
$.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/ (aggiornato da originale per sovrascrivere .html () e)
$.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');
Modifica
In alternativa, se avete intenzione di memorizzare nella cache gli elementi a cui devono essere applicati i metodi personalizzati, si potrebbe .apply()
i metodi prima di utilizzarli.
Per costruire l'esempio di cui sopra:
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