jQuery plugin design pattern for using `this` in private methods?
I'm creating jQuery plugins using the pattern from the Plugins Authoring page:
(function($) {
$.fn.myPlugin = function(settings) {
var config = {'foo': 'bar'};
if (settings) $.extend(config, settings);
this.each(function() {
// element-specific code here
});
return this;
};
})(jQuery);
My code calls for several private methods that manipulate this
. I am calling these private methods using the apply(this, arguments)
pattern. Is there a way of designing my plugin such that I don't have to call apply to pass this
from method to method?
My modified plugin code looks roughly like this:
(function($) {
$.fn.myPlugin = function(settings) {
var config = {'foo': 'bar'};
if (settings) $.extend(config, settings);
this.each(function() {
method1.apply(this);
});
return this;
};
function method1() {
// do stuff with $(this)
开发者_JS百科 method2.apply(this);
}
function method2() {
// do stuff with $(this), etc...
}
})(jQuery);
I think jQuery.proxy was created for these problems, though in general it does similar to what you do:
this.each(jQuery.proxy(method1, this));
I can suggest two ways:
This way more clearly but not exactly responsible for the task
(function( $ ) { $.fn.myPlugin = function(settings) { var config = {'foo': 'bar'}; if (settings) $.extend(config, settings); this.each(function() { method1($(this)); }); return this; }; function method1(_this) { // do stuff with _this) alert(_this.attr('id')); method2(_this); } function method2(_this) { alert(_this.attr('customAttr')); // do stuff with _this, etc... } })(jQuery);
This way is more extremally)))
(function( $ ) { var privates = { method1: function() { // do stuff with this alert(this.attr('id')); this.method2(); }, method2: function () { alert(this.attr('customAttr')); // do stuff with this, etc... } } $.fn.myPlugin = function(settings) { var config = {'foo': 'bar'}; if (settings) $.extend(config, settings); this.each(function() { var $this = $(this); $.extend($this, privates) $this.method1(); }); return this; }; })(jQuery);
Just create a scoped variable that points to this
(function($) {
var me;
$.fn.myPlugin = function(settings) {
var config = {'foo': 'bar'};
if (settings) $.extend(config, settings);
me = this;
this.each(method1);
return this;
};
function method1() {
// do stuff with me
method2();
}
function method2() {
// do stuff with me, etc...
}
})(jQuery);
精彩评论