How expensive is listening for events on the entire document?
I want to use event delegation on a number of buttons in a page of HTML. These buttons are all over the page, and I was wondering how expensive it would be to listen to the entire documen开发者_JS百科t for on click events, and then just have those on click events trigger an event delegation handler. Would this be more expensive than having listeners on each of 20+ buttons (it can grow to be over 100 buttons, yes it is silly)?
I don't see how it would be more expensive since it would be listening for clicks on the document object instead of 25 anchor objects
The key idea here is depth. Your event has to traverse up the DOM before it's being executed. If your elements are deep down the DOM tree you may notice some performance degradation.
Couple of things to bear in mind:
- the number of anchors doesn't matter for event delegation, that is true
- generally speaking event delegation is a superior alternative in most cases, but it's not useful all the time
My suggestion is to analyze these kind of problems, learn how things work, and make decisions by good old common-sense.
I don't see how it would be more expensive since it would be listening for clicks on the document object instead of 25 anchor objects. With that said, just 25-30 buttons is not really resource-intensive so you probably don't need to worry about this.
This is the strategy used by, for example, the jQuery "live" method: listen on the whole document then test the sender against a condition (i.e., selector). Unless the selector is unbearably intensive, this technique is more efficient for large and growing sets of targets.
Did you hard? working code in not a good code.
if you use 20~40 button listeners in a page, instead of using delegate then it will work and probably you will not even see any performance issue. I think you will use forin/$.each to bind all those listeners, so you will not need to write codes for each listeners.
so, my request is please use delegate.
If in future you need to change the logic or you decide to test the application then you will be in trouble.
精彩评论