tomoguisuru
tomoguisuru

Reputation: 402

jQuery Plugin - calling a public function / method

I have an image slider plugin that I've made that I want to extend some of the functionality of. I would like to make it so you can call the next method by calling the following like the jQuery UI does:

$("#elemID").imageSlider("next");

I'm kind of at a loss on how to get this done. Here is what I have so far with some of the guts missing for space.

(function($) {  
$.fn.imageSlider = function (options) {
    var options = $.extend({}, $.fn.imageSlider.defaults, options),
        obj = $(this),                          // Set it here so we only look for it once
        objID = obj.attr('id'),
        sliderName = objID + '_slider',
        total = 0,
        counterID = objID + '_ct';

    // Private Methods
    var initialize = function () {          
        if (options.jsonObject === null) {
            processAjax();
        } else {
            process(options.jsonObject);
        }

        return obj;
    }

    // Executes an AJAX call
    var processAjax = function () {
        $.ajax({
            url: options.jsonScript,
            type: 'GET',
            data: options.ajaxData,
            dataType: 'json',
            success: function (data) {
                process(data);
            },
            complete: function (jqXHR, textStatus) {
                if (options.onComplete !== $.noop) {
                    options.onComplete.call();
                }
            }
        });
    }

    var process = function (data) {
        // Generates the HTML
    }

    var changeImage = function (me, target, ops) {
        //rotate the image
    }

    $.fn.imageSlider.next = function (elemID) {
        // Currently how I call next on the slider
    }

    return initialize();
}


$.fn.imageSlider.defaults = {
    // options go here
    }
})(jQuery)

Upvotes: 2

Views: 2630

Answers (1)

Leopd
Leopd

Reputation: 42727

The standard way to do this (see docs) is to create an object called methods with stores each of your methods by name, and the actual extension looks up the the method to call by name and runs it. Like...

(function( $ ){

  var methods = {
    init : function( options ) { // THIS },
    process : function( ) { // IS   },
    changeImage : function( ) { // GOOD },
    next : function( content ) { // !!! }
  };

  $.fn.imageSlider = function( method ) {

    // Method calling logic
    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.imageSlider' );
    }    

  };

})( jQuery );

Upvotes: 1

Related Questions