Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is .unbind().click(function() {...}) a good practice?

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.

like image 734
Jackie Chan Avatar asked Dec 09 '22 21:12

Jackie Chan


1 Answers

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:

$(selector).off('click.namespace').on('click.namespace', function(e) { //...

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) 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) { //...


Performance?

If you wonder about the performance of the different handlers:

Check out this performance test here

like image 158
Beat Richartz Avatar answered Dec 27 '22 23:12

Beat Richartz