jQuery plugin design pattern for using `this` in private methods?
- by thebossman
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)
method2.apply(this);
}
function method2() {
// do stuff with $(this), etc...
}
})(jQuery);