user3573535 user3573535 - 4 months ago 11
jQuery Question

Unbind some event handlers with namespaces

I want to ask, how can I remove event handlers from the

document
, but only those with a namespace?

I have this piece of code, I see no errors, but this function always fires the event handlers for
mouseup
and
touchend
even after
.unbind
. I'm sure that I have some errors in this code.

$(".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");
}
}
});
});


Thanks for advice

Answer

Firstly, on() and off() are now the preferred methods instead of the outdated bind() and unbind().

Secondly, to fix your issue you should separate the events with a space, not a comma. Try this:

$(".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");
            }
        }
    });
});

Also note that if you want to turn off all events associated with a namespace you can pass the namespace alone to the off() method:

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