Me preguntaba por qué en tantos plugins de jquery $ (esto) está configurado para apuntar a $ this, aquí hay un ejemplo, si tengo los siguientes dos complementos incluidos en una página:
(function($) {
jQuery.fn.pluginOne = function() {
return this.each(function() {
$this = $(this); <--
alert($this);
});
};
})(jQuery)
(function($) {
jQuery.fn.pluginTwo = function() {
return this.each(function() {
$this = $(this); <--
alert($this);
});
};
})(jQuery)
cuando llamo ambos plugins en listo dom:
$(document).ready({
$('.myClass').pluginOne();
$('.myOtherClass').pluginTwo();
});
el primer plugin obtendrá $ esto desde el segundo complemento ... mientras señalo $ (este) a una var local:
(function($) {
jQuery.fn.pluginTwo = function() {
return this.each(function() {
var trigger = $(this); <--
alert(trigger);
});
};
})(jQuery)
todo funciona como debería, por supuesto ...
Así que mi pregunta es ... ¿cuándo debería usar $ this?
Gracias
Sólo para aclarar ... En el ejemplo anterior $ (' MyOtherClass.) PluginTwo (.); devolverá el primer elemento de la siguiente matriz: $ ('.myClass') –