JavaScript: Is there any performance benefit to stopping event propagation?

∥☆過路亽.° 提交于 2019-12-10 12:17:59

问题


Is it considered 'good practice' to stop JavaScript event propagation - does it benefit performance in any way?

I'm wondering if there is benefit outside of layout purposes where you stop propagation so you don't trigger multiple events accidentially.


回答1:


Only when it is necessary to the program logic, such as to prevent form submission or another DOM element's action being triggered. Unless you have a seriously complex DOM tree, there will not be any serious performance hit.




回答2:


It entirely depends on the DOM complexity and the actions taken in each event that is triggered.

You would stop propagating events mainly not because of complexity but because of unwanted actions not to take place.

For eg: Consider a situation where you have a show hide div and when you click on the div it should opne and if you click anywhere else in the document it should close.

So you would wire an onclick event handler to the document as well as the div. So you have to stop propagating the event when clicked on the div so that the document click handler won't be invoked. Thats a situation where you use stop event propagtion.



来源:https://stackoverflow.com/questions/1464482/javascript-is-there-any-performance-benefit-to-stopping-event-propagation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!