I'm using Addy Osmani's excellent jQuery plugin pattern to write a jQuery plugin (http://addyosmani.com/resources/essentialjsdesignpatterns/book/#jquerypluginpatterns), but there's something that confuses me about the way he adds functions to the prototype:
// The actual plugin constructor
function Plugin( element, options ) {
this.element = element;
// jQuery has an extend method that merges the
// contents of two or more objects, storing the
// result in the first object. The first object
// is generally empty because we don't want to alter
// the default options for future instances of the plugin
this.options = $.extend( {}, defaults, options) ;
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype.init = function () {
// Place initialization logic here
// We already have access to the DOM element and
// the options via the instance, e.g. this.element
// and this.options
};
In this section he calls "this.init()", which is a function added to the Plugin's prototype, but if I add my own functions to the prototype, I can't call it from anywhere where 'this' changes scope.
E.g.
Plugin.prototype.foo = function() {};
can't be called from:
$('.some-class).each(function() {
this.foo();
});
because 'this' refers to each element in the selection.
How do I call methods and functions from the plugin in a standard way? These approaches don't work either:
Plugin.foo();
this.foo();
Edit: actual code:
;(function ($, window, document, undefined) {
var pluginName = 'slider',
defaults = {
speed: 1000,
pause: 5000
};
function Plugin(element, options) {
this.element = element;
this.options = $.extend( {}, defaults, options) ;
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype.init = function () {
var $slider,
$controls;
$slider = $(this.element);
$controls = $slider.find('.slider__controls');
$controls.each(function(index) {
// How do I call 'showControl();'?
});
};
Plugin.prototype.showControl = function() {
// Do things.
};
$.fn[pluginName] = function (options) {
return this.each(function () {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName, new Plugin(this, options));
}
});
}
})(jQuery, window, document);