2012-03-08 64 views
2

我想開發一個插件,將回調作爲init的第一個參數。我試圖修改官方tutorial的插件代碼。我想不通爲什麼什麼是錯在這裏:麻煩傳遞迴調給我的jquery插件

插件:

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

的錯誤:

Method function(){alert('hey');} does not exist on jQuery.myplugin

回答

2

這條線:

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

是造成$.error條件(上接else子句中)火了,因爲你檢查的方法名稱或選擇對象,並沒有考慮在傳遞一個參數類型的函數。

我建議讓您的options對象的callback選項一部分,而不是:

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

+0

是的,這也在情理之中感謝 – Yarin 2012-03-08 16:55:58