1

当我申请 on()-handlers 时,如果我有多个申请,我更喜欢以下表示法:

$(window).on({
    keyup: function (e) {
        applyKeyEvents(e, modal);
    },
    click: function (e) {
        applyMouseEvents(e, modal);
}

有谁知道如何在这个符号中设置一个命名空间?

在这种情况下,我通过回退到单个符号解决了这个问题:

$(window).on('click.modalClickClose', function (e) {
    applyMouseEvents(e, modal);
});

$(window).on('keyup.modalKeyClose', function (e) {
    applyKeyEvents(e, modal);
});

但我真的很讨厌重复自己。将 off() 方法与多个处理程序一起使用的相同问题/问题。

这有效:

$(window).off('click.modalClickClose');
$(window).off('keyup.modalKeyClose');

我敢打赌 off() 是一件容易的事,但在过去 15 小时编码后我没有得到它。

4

1 回答 1

2

If you're passing an object to .on() to list more than one event you can (as with any JavaScript object literal) put the property names in quotes if you need the property names to include a dot:

$(window).on({
    "keyup.modalKeyClose" : function (e) {
        applyKeyEvents(e, modal);
    },
    "click.modalClickClose" : function (e) {
        applyMouseEvents(e, modal);
    }
});

According to the .off() documentation you can remove multiple handlers with one call by listing all the handlers in the same string, with or without namespaces:

$(window).off("keyup.modalKeyClose click.modalClickClose");

Note that if you were to give both of your events the same namespace:

$(window).on({
    "keyup.modalClose" : function (e) {
        applyKeyEvents(e, modal);
    },
    "click.modalClose" : function (e) {
        applyMouseEvents(e, modal);
    }
});

...then you could remove them by specifying just the namespace:

$(window).off(".modalClose");
于 2013-07-28T01:27:50.380 回答