Domanda

When I apply on()-handlers I prefer the following notation if I have more than one to apply:

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

Does anybody knows how to set a namespace within this notation?

I solved the problem in this case with falling back to a single notation:

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

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

But I really hate to repeat myself. Same issue/question for using the off()-method with more than one handler.

This works:

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

I bet the off()-thing is a easy one, but I don't get it after coding the last 15 hours.

È stato utile?

Soluzione

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");
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top