将某些事件处理程序与命名空间取消绑定

Unbind some event handlers with namespaces

本文关键字:命名空间 取消 绑定 程序 事件处理      更新时间:2023-09-26
我想

问一下,如何从document中删除事件处理程序,而只删除那些带有命名空间的事件处理程序?

我有这段代码,我没有看到任何错误,但是即使在.unbind之后,此函数也始终触发mouseuptouchend的事件处理程序。我确定我在此代码中有一些错误。

$(".inp").on("autocompleteresponse", function(event, ui) {
    $(document).bind( "mouseup.test, touchend.test", function(e) {
        var container = $('.ui-autocomplete');
        if (!container.is(e.target) && container.has(e.target).length === 0) {
            if (ui.content.length > 0) {
                ui.item = ui.content[0];
                console.log (ui.item);
                $(".inp").val(ui.item.label);
                // This will fire always, on document click, should only once per time
                $(document).unbind("mouseup.test, touchend.test");
            }
        }
    });
});

感谢您的建议

首先,on()off()现在是首选方法,而不是过时的bind()unbind()

其次,要解决您的问题,您应该用空格而不是逗号分隔事件。试试这个:

$(".inp").on("autocompleteresponse", function(event, ui) {
    $(document).on("mouseup.test touchend.test", function(e) {
        var container = $('.ui-autocomplete');
        if (!container.is(e.target) && container.has(e.target).length === 0) {
            if (ui.content.length > 0) {
                ui.item = ui.content[0];
                console.log(ui.item);
                $(".inp").val(ui.item.label);
                $(document).off("mouseup.test touchend.test");
            }
        }
    });
});

另请注意,如果要关闭与命名空间关联的所有事件,可以将命名空间单独传递给 off() 方法:

$(document).off(".test")