Im porting a prototype plugin to jQuery.
The plugin uses the proscribed method of collecting all the plugins methods in an object literal and then calling them like [object].[method]
What I dont understand is, in any of those methods there is use of properties (defined at the begging of the script i.e. var x = 0, var y = 0, etc) that appear to be global and not passed as arguments or properties of a specific method.
How would I do this in jQuery and is it possible?
Please refer to ‘var1’ in the code below. Where would this be set so that all methods have access to it?
Example:
;(function($){
var methods = {
init : function(options) {
var config = {
// default options...
}
// overide config
var settings = $.extend(config, options);
return this.each(function() {
// init code goes here...
});
},
function1 : function() {
function2();
},
function2 : function() {
$(selector).css({
width : var1,
});
},
}
$.fn.[PLUGINNAME] = 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.tooltip' );
}
};
})(jQuery);
You need to declare the variable inside the self-evoking function, but outside any other function.
You could then use the init method to set the proper value to it for instance, if it is part of the initialization process, and not just a static variable.
Since JavaScript uses functions to declare variable scope, the outer self-evoking function will make sure that the variable don’t “leak” up to the global scope, but since it is declare outside any of the inner functions, it will be available to all functions within your plugin.