0

我正在构建一个 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但不知道如何去做。

提前致谢。

4

2 回答 2

0

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

$.myplugin = function () {
   ...
   return $('body');
};
于 2012-11-21T15:29:25.750 回答
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().

干杯。

于 2012-11-21T16:26:03.193 回答