Infinite recursion in jQuery plugin subfunction
I wrote the following jQuery plugin:
(function($){
$.fn.imageSlide = fun开发者_StackOverflow中文版ction(options){
$(this).imageSlide.nextSlide();
console.log("imageslide");
};
$.fn.imageSlide.nextSlide = function(){
console.log("nextslide");
$this = $(this);
};
})(jQuery);
Some background:
I want an image slider plugin, to crossfade backgrounds (for performance reasons I cannot use the Supersized plugin). I want to expose several functions to the user: the imageSlide plugin "constructor" and several other functions, e.g. imageSlide.nextSlide
and imageSlide.previousSlide
, to enable the user to perform these actions from outside the plugin.
The imageSlide
function needs to call the imageSlide.nextSlide function
, to slide in (or fade in) the first image.
Problem:
It seems that the line $this = $(this);
triggers an infinite recursion of the imageSlide.nextSlide
function.
- Why is this happening?
- It seems that
$.fn.imageSlide.nextSlide = function(){};
is not the right way to expose another function in a jQuery plugin. How am I supposed to do this?
I'm not sure exactly what is causing the error, but there is no need to put all your static methods in the jQuery prototype.
Try exposing the plugin using something like:
(function($) {
// The constructor of your plugin:
var imageSlide = function(elems, options) {
this.elems = elems; // the targets from the jQuery selector
this.options = options;
};
// the public inherited methods:
imageSlide.prototype = {
nextSlide: function() {
console.log('nextSlide called');
}
};
// extending the jQuery prototype and returning only one instance:
$.fn.imageSlide = function(options) {
return new imageSlide(this, options);
};
})(jQuery);
Now you can call the plugin and it's methods like this:
var myGallery = $('#gallery').imageSlide();
myGallery.nextSlide();
精彩评论