Something u maybe ignore about event delegate and element selector in jQuery

已销号 发布于 2016/09/04 14:01
阅读 119
收藏 0

In a web project, I want to delegate all elements click event in a function, and call specify event handle function with data attribute in the element.
At first, I try to delegate click event in document body tag using on function:

bind: {
  events: function(){
    $(document).on('click', function(e){ console.log("click"); var behavior = $(e.target).attr("data-behavior"); if ( behavior !== undefined ) { eval("App.events." + behavior + "();");
      }
    })
  }
},
events: {
  homeScrollNext: function(){ // some behavior },
  homeContactMe: function(){ // some behavior }
}

After i view the jQuery document about on function Event performance, I feel so ashame of above code I wrote. It reduce the performance

Attaching many delegated event handlers near the top of the document tree can degrade performance. Each time the event occurs, jQuery must compare all selectors of all attached events of that type to every element in the path from the event target up to the top of the document. For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use of document or document.body for delegated events on large documents.

too young too simple as president Jiang say.
So, I begin to find a better way to achieve my goal...

jQuery can process simple selectors of the form tag#id.class very quickly when they are used to filter delegated events.

limiting the query scope for selector is a good way to increase the query elements performance. As all elements I want to bind click event have an data-behaviorattribute,so I can use it for on function second param to limit the selectors.

bind: {
  events: function(){
    $(document).on('click',"*[data-behavior]", function(e){ console.log("click"); var behavior = $(e.target).attr("data-behavior"); if ( behavior !== undefined ) { eval("App.events." + behavior + "();");
      }
    })
  }
},
events: {
  homeScrollNext: function(){},
  homeContactMe: function(){}
}

Maybe it's the best solution for my situation....
There is also shortcut when Using data attribute to find HTML elements, which had been mention by Don’t use data attributes to find HTML elements with JS

加载中
返回顶部
顶部