jQuery: Is it illegal or bad practice to assign multiple event handlers? [duplicate]

China☆狼群 提交于 2019-12-04 18:01:49

Having two events is no problem. You can assign as many events to an object as you like.

This is logical as you most likely want different functions to fire depending on the event that's triggered. And 99% of every jQuery-plugin will have no problem dealing with objects with multiple events. Try it and ask a question if you have any problems.

The only thing that is not good is inline js ;)

Selvakumar Arumugam

It would NOT break any handler that was bound already. The way jQuery bind is using event registration model and so it support multiple event handlers.

This is one of the advantages in using addEventListeners/attachEvent over traditional methods.

More reading: https://stackoverflow.com/a/12627478/297641

Not really, though if you can handle all functionality in one handler, then why wouldn't you?

You should have no problem. Just add your own event handler using jQuery's API and you'll be set. From the jQuery Docs on .on():

As of jQuery 1.4, the same event handler can be bound to an element multiple times.

$('#myButton').on('click', myHandler)

In some cases I would say it is bad practice. Creating multiple event handlers on a single element is almost always avoidable. If you are comfortable enough, you could always open the source of the plugin(if its not a minified version) and modify the event handler to include your modifications.

If you are uncomfortable doing that, then I would say continue what you are doing. Just know that there are better alternatives.

This assumes that you are adding say another click event binding when the plugin already has one.

-Mike

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