2011-01-12 82 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);