I am using the following project to create jQuery plugins. I'm pretty sure I got the concept from the jQuery main page, however it is no longer published there.
I recently tried to access a variable settingsin a method (i.e. someOtherMethod ()) different from the method init(), and experienced an error because settingsit was not defined. I see the reason, because it is settingsisolated from the method init().
If I move settingsoutside this method, I could access it from different methods, however, each instance, when the plugin is applied, will not have its own unique parameter variable, which is unacceptable. For example, it $('#id1, #id2').myPlugin({x:111});must have a common variable settings, but it $('#id1').myPlugin({x:111}); $('#id2').myPlugin({x:222});must have its own unique configuration variable.
Given the design pattern below as a starting point, how can I access a variable settingsfrom all the methods associated with the plugin, but does it have a unique variable each time it is used settings?
(function( $ ){
var defaults={
x : 123,
y : 321
};
var methods = {
init : function( options ) {
var settings = $.extend(defaults, options || {});
return this.each(function(){
});
},
someOtherMethod : function() {
return $(this).each(function(){
})
},
};
$.fn.myPlugin = function(method) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.myPlugin' );
}
};
}( jQuery ));
$('#id1, #id2').myPlugin({x:111});
$('#id3').myPlugin({x:333});
$('#id3').myPlugin('someOtherMethod');
source
share