I’m talking about the following:
.unbind().click(function () {
// Do something
}
It looks a bit dodgy to me, however it makes sense: the developer wants to first remove any events bound to the element and then bind a click event.
Is there a better solution for this issue? Or correct my way of thinking.
It’s not really good practice, because you do not control which click events get unbound. There are two different approaches to improve this:
Use event namespaces (faster)
You can use a namespace to control you unbind just the click event you’re going to bind again:
Use classes (fastest)
Use classes added to the link to mark it as registered (this does not unbind previously bound events, but it helps preventing multiple event bindings, which is the issue in most cases you would use
off(unbind) beforeon(bind):You can even turn this into a little sexy plugin, writing:
Like this, you can just call
registeron every selector:Or with a specific class, if «registered» is taken:
Performance?
If you wonder about the performance of the different handlers:
Check out this performance test here