2011-01-12 71 views
2

我正在寫一個jQuery插件,但當我處理事件時,我被卡住了。在jQuery插件中處理事件

例如,我希望用戶能夠指定一個函數來處理我保存事件

他會配置它這樣

$(".foo").bar({ 
    save: function (x,y){ 
    alert("whatever"); 
    }) 
}); 

但我不知道該怎麼稱呼,從我的插件以及如何傳遞參數...

感謝您的閱讀!

回答

2

你的插件代碼會是這個樣子:

$.fn.bar = function(options) { 
    options = $.extend({}, {/*your default options*/}, options); 
}); 

當你要撥打的用戶提供的函數,調用它:

options.save(x, y); // or whatever x and y are 

如果你要撥打的函數,使變量this在該函數中具有有用的含義,請使用call

options.save.call(somevar, x, y); 

這設置this在您的回調到somevar。如果,例如,你想要的回調有選擇到bar被稱爲上,你可以做options.save.call(this, x y);

+1

尼斯解釋,但你要翻轉「$ .extend」中`options`和`defaults`的位置。 :o) – user113716 2011-01-12 20:53:24

2
(function($) { 
    $.fn.bar = function(opts) { 
      // reference the function from the options passed 
     var theFunc = opts.save; 
      // call the function 
     theFunc(); 
     // or call the function from the context of the jQuery object 
     // and pass it the proper arguments 
     theFunc.call(this, 'someX', 'someY'); 
    }; 
})(jQuery); 
1

嘗試做一些這樣的:

(function($) { 
    $.fn.bar = function(options) { 

     // Extend default config with config object passed at invocation time 
     options = $.extend({ 
      ... 

     }, options); 

     // Check that Callback function has been passed 
     if (options.save) { 

      var newVar = ...; 

      // Delegate the function to some variable (it will act as *this* in the called 
      // function). You can pass few arguments as well 
      options.save.call(newVar, arg1, arg2) 
     } 

    }; 
})(jQuery);