I know that we can attach events with the jQuery on()
function and remove them again with off()
.
In an existing project I do sometimes come across code similar to this:
$("#SomeId").off("click").on("click");
or sometimes when using namespacing similar to this:
$("#SomeId").off("click.namespace").on("click.namespace");
As far as I know you can only attach a single event to a specific namespace of the event.
For example if I simply do on("click")
it will attach my specified function, overwriting the current function assigned, adding to the "click" event.
If I do on("click.namespace")
it will attach my specified function overwriting the current function assigned, adding to the click.namespace
.
What is the point removing any events by chaining an off("click")
to the on("click)
if on()
already replaces any functions assigned to the specified event/event.namespace?
Is it redundant syntax in our code or is there a reason for it which I have missed?
Edit - Thank you kapa
I feel a bit silly now, I corrected my faulty knowledge above. Executing on("click.namespace1")
several times I observed now that the data("events")
object kept adding to the click event array.
I think that answers my own question there. That is why one would use off("event.namespace")
to ensure nothing else is attached to that exact event/event.namespace.