I’m new with jquery plugin authoring and wonder how a method in the plugin can call another method inside the same plugin.
In the sample code I’m trying to call f2 from f1 but I have a js error because of this.each() in the f2 method.
Can you enlighten me ?
Thanks
Edit : f1() and f2() can be called from outside the plugin $.pluginName(‘f1’) and $.pluginName(‘f2’).
What I want is to call f2() after somme code in f1().
;
(function( $ ){
'use strict';
var pluginName = 'pluginName';
var defaults = {
};
var methods = {
init : function( options ) {
return this.each(function ( ) {
var $this = $(this);
var settings = $.extend({}, defaults, options);
$this.data(pluginName, settings);
return $this;
});
},
f1 : function() {
methods.f2(); // Uncaught TypeError: Object #<Object> has no method 'each'
},
f2 : function() {
return this.each(function() {
});
}
};
$.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.' + pluginName + '()');
}
};
})( jQuery );
This is showing error because when you call
f2()fromf1()You are not passing the jQuery objects tof2()sothiswont refer to the same object insidef2()and hence it wont work.So change your
f1()code like thisIt’s specifying what
thiswill mean insidef2(). And in this case we are passing the jQuery object.Working Example
More on .apply