jQuery插件 - 调用公共函数/方法

时间:2011-08-09 16:07:47

标签: jquery jquery-plugins

我有一个图像滑块插件,我已经制作,我想扩展一些功能。我想这样做,所以你可以像调用jQuery UI一样调用下面的方法:

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

我对如何完成这件事感到茫然。到目前为止,这里有一些缺少空间的内容。

(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)

1 个答案:

答案 0 :(得分:1)

执行此操作的标准方法(see docs)是创建一个名为methods的对象,并按名称存储每个方法,实际扩展名查找要按名称调用的方法跑吧。像...

(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 );