麻烦将回调传递给我的jquery插件

时间:2012-03-08 16:03:39

标签: jquery jquery-plugins

我正在尝试开发一个插件,它将回调作为init的第一个参数。我试图修改官方tutorial的插件代码。我无法弄清楚为什么这里有什么问题:

插件:

(function( $ ){

    var methods = {

        init : function( callback, options ) { 

            // Create some defaults, extending them with any options that were provided
            var settings = $.extend( {
                'location'         : 'top',
                'background-color' : 'blue'
                }, options);


            return this.each(function() {        

                $this.click(function(e) {

                    e.stopPropagation();
                    var $target = $(e.target);
                    if (callback) 
                        callback($target);
                });

            });
        },

    };

    $.fn.myplugin = 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.myplugin' );
        }

    };

})( jQuery );

调用插件:

// Create callback function
var callback = function(){alert('hey');};

$('#my-control').myplugin(callback,{'width':'600px'}); 

错误:

  

方法函数(){alert('hey');}在jQuery.myplugin上不存在

1 个答案:

答案 0 :(得分:2)

这一行:

else if ( typeof method === 'object' || ! method ) {

导致$.error条件(在下一个else子句中)被触发,因为您正在检查方法名称或选项对象,并且没有考虑传入参数类型功能。

我建议改为callback对象的options选项部分:

(function($) {

    var methods = {

        init: function(options) {
            console.dir(arguments);
            // Create some defaults, extending them with any options that were provided
            var settings = $.extend({
                'location': 'top',
                'background-color': 'blue'
            }, options);


            return this.each(function() {

                $(this).click(function(e) {

                    e.stopPropagation();
                    var $target = $(e.target);
                    if (settings.callback) settings.callback($target);
                });

            });
        },

    };

    $.fn.myplugin = 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.myplugin');
        }

    };

})(jQuery);

用法:

var callback = function(){alert('hey');};
$('#my-control').myplugin({'width':'600px', callback: callback}); 

示例: http://jsfiddle.net/n66mU/