同时扩展JQuery插件和JQuery

时间:2012-11-21 15:18:31

标签: javascript jquery

我正在构建一个Jquery插件。我的骨架代码如下:

(function (window, document, $, undefined) {

    var methods = {
        init : function(options){
        },
        func_1: function(){
        },
        func_2: function(){
        }
    };

    $.fn.myplugin = function(args){

        if ( methods[args] )
        {
            return methods[ args ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        }
        else if ( typeof args === 'object' || ! args ) 
        {
            var opts = $.extend({}, $.fn.myplugin.defaults, args);
            var new_args = new Array(opts);
            return methods.init.apply( this, new_args );
        }
        else 
        {
            $.error( 'Method ' +  args + ' does not exist' );
        }
    };

    $.fn.myplugin.defaults = {
         func_1: function(){},
         func_2: function(){}
    };

}(window, document, jQuery));

我正在寻求扩展此插件,以便我可以向JQuery添加其他功能。所以,我希望将这些函数调用如下:

$.myplugin.new_func();

我该怎么做?我知道我可能不得不使用$.extend,但不知道如何去做。

提前致谢。

2 个答案:

答案 0 :(得分:0)

$ .fn.myplugin和$ .myplugin之间的区别在于后者没有任何上下文。因此,您可以使用以下代码定义后者。为了对$ .myplugin的结果使用链接,你只需要返回一个你想要使用.new_func()方法的对象,例如某个jQuery对象。

$.myplugin = function () {
   ...
   return $('body');
};

答案 1 :(得分:0)

好的,经过一些较旧的JQuery插件(尤其是FancyBox 2)后,我设法找到了一种方法。以下是整个框架代码:

(function (window, document, $, undefined) {

    var methods = {
        init : function(options){
        },
        func_1: function(){
        },
        func_2: function(){
        }
    };

    $.fn.myplugin = function(args){

        if ( methods[args] )
        {
            return methods[ args ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        }
        else if ( typeof args === 'object' || ! args ) 
        {
            var opts = $.extend({}, $.fn.myplugin.defaults, args);
            var new_args = new Array(opts);
            return methods.init.apply( this, new_args );
        }
        else 
        {
            $.error( 'Method ' +  args + ' does not exist' );
        }
    };

    $.fn.myplugin.defaults = {
        func_1:     function(){},
        func_2:     function(){}
    };

    //below is the code I added to get the desired functionality
    var D = $.myplugin = function(){};
    $.extend(D, {
        new_func: function(){
            //add functionality here
        }
    });

}(window, document, jQuery));

也可以在new_func对象中定义一个函数(称为methods或其他),然后使用methods.new_func()从新函数中调用它。

干杯。