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:
You can use a namespace to control you unbind just the click event you're going to bind again:
$(selector).off('click.namespace').on('click.namespace', function(e) { //...
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) before on
(bind):
$(selector).not('.registered').addClass('registered').on('click', function(e) { //...
You can even turn this into a little sexy plugin, writing:
$.fn.register = function(register_class) {
register_class || (register_class = 'registered'); // lets you control the class
return this.not('.' + register_class).addClass(register_class);
};
Like this, you can just call register
on every selector:
$(selector).register().on('click', function(e) { //...
Or with a specific class, if «registered» is taken:
$(selector).register('special_handler_registered').on('click', function(e) { //...
Check out this performance test here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With