处理jQuery插件中的事件 [英] Handle events in a jQuery plugin

查看:86
本文介绍了处理jQuery插件中的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个jQuery插件,但是在处理事件时被卡住了.

I'm writing a jQuery plugin but I'm stuck when I'm handling events.

例如,我希望用户能够指定一个函数来处理我的保存事件

For example I want the user to be able to specify a function to handle my save event

他会这样配置

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

但是我不知道如何从我的插件中调用它以及如何传递参数...

But I dont know how to call that from my plugin and how to pass arguments...

感谢您的阅读!

推荐答案

您的插件代码将如下所示:

Your plugin code will look something like this:

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

要调用用户提供的函数时,请调用它:

When you want to call the user-supplied function, call it:

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

如果要调用该函数以使变量this在该函数中具有有用的含义,请使用

If you want to call the function so that the variable this has a useful meaning within that function, use call:

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

这会将回调中的this设置为somevar.例如,如果您希望回调具有调用了bar的选择,则可以执行options.save.call(this, x y);

This sets this within your callback to somevar. If, for example, you wanted the callback to have the selection that bar was called on, you could do options.save.call(this, x y);

这篇关于处理jQuery插件中的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆