Is there way to write this shorter or more efficient?

105 Views Asked by At

I have ten blocks of code like this, it is all for dynamically created content:

$(document).on('click', '.item' , function() {
    //... do something
});

$(document).on('click', '.element' , function() {
    //... do something different
});

Is there a way to write this shorter or more efficient?

3

There are 3 best solutions below

0
On BEST ANSWER

You could cache your document selector.

var $document = $(document);

$document.on('click', '.item' , function() {
    //... do something
});

$document.on('click', '.element' , function() {
    //... do something different
});

But that's about it.

Edit: Contribute a test to my jsPerf if you want hard data.

0
On

Unfortunately, it's not. That's the only way because content inside the function is different

5
On

One thing you could do is create a map between selectors and handlers:

var handlers = {
  '.item' : function() {
    //... do something
   },

  '.element' : function() {
    //... do something different
  }
}

Then you can assign the handlers in one swift iteration:

var $doc = $(document); // no need to wrap the document each time
for (var selector in handlers) {
  if (handlers.hasOwnProperty(selector))
    $doc.on('click', selector, handlers[selector]);      
}

One more comment (see @ArunPJohny's comment), regarding efficiency. If you can get away with assigning the handler to an element lower in the DOM tree (farther from document), you should. In this construct:

$(static).on('click', dynamic, f);

For each click event that reaches an element in the $(static) collection, the dynamic selector is matched to see if f should be triggered. If static is the document, then all clicks in the page will be matched. If you can get a more specific element, less clicks will be matched. For clicks you might not notice a big difference, but events that are triggered faster (mousemove) may give you trouble.