Reputation: 1114
I'm a newbie in JQuery , I've always wondering why some developers frequently use this syntax:
$("#someElem").off("change").on("change", function () { //TODO: })
,
to bind some event ?
Is it any advantages to using it this way, instead of just to use
$("#someElem").on("change", function () { //TODO: })
,
is it best practice to add off() method before, and what reason for doing it this way ?
Upvotes: 1
Views: 62
Reputation: 59232
Is it any advantages to using it this way
What they're trying to do is remove any potential handlers, that were already attached to the Element.
So, it is to make sure that the only handler that will be called is the one which is currently provided.
If off
is not called, the current handler will be called along with some previously attached handlers. It doesn't overwrite, instead executes all the handlers that are set.
If you know what you're doing, then you do not need to call off
, but it isn't called "best practice", but more of a hack as @adeneo said.
Upvotes: 1