Infinite recursion in jQuery plugin subfunction -
i wrote following jquery plugin:
(function($){ $.fn.imageslide = function(options){ $(this).imageslide.nextslide(); console.log("imageslide"); }; $.fn.imageslide.nextslide = function(){ console.log("nextslide"); $this = $(this); }; })(jquery);
some background:
i want image slider plugin, crossfade backgrounds (for performance reasons cannot use supersized plugin). want expose several functions user: imageslide plugin "constructor" , several other functions, e.g. imageslide.nextslide
, imageslide.previousslide
, enable user perform these actions outside plugin.
the imageslide
function needs call imageslide.nextslide function
, slide in (or fade in) first image.
problem:
it seems line $this = $(this);
triggers infinite recursion of imageslide.nextslide
function.
- why happening?
- it seems
$.fn.imageslide.nextslide = function(){};
not right way expose function in jquery plugin. how supposed this?
i'm not sure causing error, there no need put static methods in jquery prototype.
try exposing plugin using like:
(function($) { // constructor of plugin: var imageslide = function(elems, options) { this.elems = elems; // targets jquery selector this.options = options; }; // public inherited methods: imageslide.prototype = { nextslide: function() { console.log('nextslide called'); } }; // extending jquery prototype , returning 1 instance: $.fn.imageslide = function(options) { return new imageslide(this, options); }; })(jquery);
now can call plugin , it's methods this:
var mygallery = $('#gallery').imageslide(); mygallery.nextslide();
Comments
Post a Comment