jQuery点击事件可以解除绑定还是重置? [英] Can jQuery click events be unbound or reset?

查看:1063
本文介绍了jQuery点击事件可以解除绑定还是重置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现我正在处理的网页上有资源泄漏。

I've discovered a resource leak on a webpage I'm working on.

此网页有两个文本字段,点击后显示模态对话框,执行数据请求到后端,然后在表中显示该信息,用户可以从中选择一个条目,以便在他们最初点击的文本框中使用。

This webpage has two textfields, that upon click show a modal dialog, perform a data request to the backend, and then present that information in a table that the user can select an entry from for use in the textbox they originally clicked.

我有约束力单击事件到文本框,如下所示:

I'm binding the click events to the textboxes like so:

var $field = $('#one-of-the-text-fields');

$field.click(function () {
        App.DialogClass.show();
        App.DialogClass.PopulateTable();
        App.DialogClass.GotoPageButtonAction(actionArgs);  // Offender!
});

...哪些电话......

...Which calls...

App.DialogClass = (function($) {

var pub {},
    $gotoPage = $('#pageNumberNavigationField'),
    $gotoPageButton = $('#pageNumberNavigationButton');

// ...SNIP unimportant other details...

pub.GotoPageButtonAction = function (args) {
    $gotoPageButton.click(function () {
        var pageNumber = $gotoPage.val();
        pub.PopulateTable(args);   // Breakpoint inserted here...
    });
};

return pub;

})(jQuery);

我注意到泄漏,因为当我使用Chrome的JavaScript调试器时,我总是有一个额外的每次我点击一个不同的按钮时断点(例如,我第一次点击字段A,断点被击中两次。当我在那之后击中字段B时,断点被击中三次。如果我在之后点击A ,断点被击中四次。根据需要进行推断。)

I noticed the leak because when I ran through using Chrome's JavaScript debugger, I'm always having one extra breakpoint hit every time I click a different button (e.g. the first time I click field A, the breakpoint is hit twice. When I hit field B after that, the break point is hit three times. If I click A after that, the breakpoint is hit four times. Extrapolate as necessary.)

我的代码中没有任何关于给定字段的现有点击事件的任何事情。我怀疑我的泄漏是因为事件没有得到清理。话虽这么说,我对JavaScript / jQuery也不是很熟悉。从控件中删除点击事件有哪些技巧?

Nowhere in my code am I doing anything about an existing click event for a given field. I suspect my leak stems from the fact that the events are not getting cleaned up. That being said, I am also not terribly familiar with JavaScript/jQuery. What are some techniques for removing click events from a control?

推荐答案

当然。解开它们:

$field.unbind('click');

但请记住,这将删除所有事件处理程序以进行点击,而不仅仅是你的。为安全起见,您应该在绑定处理程序时使用名称空间:

However, bear in mind that this will remove all event handlers for click, not just yours. For safety, you should use namespaces when binding handlers:

$field.bind('click.mynamespace', function(){
    // do something
});

然后,

$field.unbind('click.mynamespace');

那么,只会删除你的处理程序。

So, then, only your handler will be removed.

这篇关于jQuery点击事件可以解除绑定还是重置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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