views:

32

answers:

1

I wrote the 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 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?
A: 

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();
David
Does this return a jQuery object? I want to call the subfunctions directly on the jQuery object, like this: `$('#gallery').imageSlide.nextSlide()`; this way I only pollute one "namespace" (imageSlide) for my plugin, but I don't need to keep track of the image sliders I have created.
Scharrels
Yes, you can chain them like that using `$('#gallery').imageSlide().nextSlide();` but that will create a new instance.
David