这个 jQuery 触发器有多贵?
这个 jsFiddle 演示了我在说什么。本质上,我将一些元素绑定到自定义事件,然后使用
$('*').trigger('myevent', args)
我这样做来调用触发器,因为我将有一些元素绑定到此事件,但我还不知道它们是什么,我会希望尽可能地解耦这段代码。调用 $('*').trigger
是否昂贵得离谱,或者因为它只会触发绑定到该事件的元素而没有那么昂贵?
换句话说,这段代码是否会遍历页面上的每个元素以查看它是否附加到此事件,或者它是否知道哪些元素附加到该事件并只是触发它们?如果是前者,有更好的解决办法吗?
This jsFiddle demonstrates what I'm talking about. Essentially, I'm binding some elements to a custom event and then calling a trigger using
$('*').trigger('myevent', args)
I'm doing this because I will have some elements bound to this event, but I don't know what they will be yet, and I'd like to decouple this code as much as possible. Is it ridiculously expensive to call $('*').trigger
or not that expensive since it will only trigger the elements that are bound to that event?
In other words, does this code go through every element on the page to see if it is attached to this event, or does it know which ones are and just triggers them? If the former is the case, is there a better solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
更好的解决方案是绑定并触发文档中的事件,因为它只是一个 DOM 元素:
现在,最终听起来更好的解决方案是使用事件委托:
看一下 < a href="http://api.jquery.com/delegate/" rel="nofollow">http://api.jquery.com/delegate/
The better solution is to bind and trigger events off of the document, since it will only be one DOM element:
Now ultimately what sounds like an even better solution to your problem would be to use event delegation:
Take a look at this example from http://api.jquery.com/delegate/
你有没有想过pubsub?就像简单的事情一样。
或者删除 jQuery 依赖
amplify.subscribe 和 Backbone.Events 为此有特定的对象。您甚至可能会找到具有类似对象的其他库。甚至还有用于此目的的库 PubSub.js 。
示例:
一般来说,
pub
是trigger
,sub
是bind
。在这个特定的示例中,我们有两个独立的插件。他们不知道他们是否意见一致,或者根本不知道他们是否在交谈。但由于排序“破坏”了我们表上的分页插件,我们订阅了排序“事件”来修复我们的分页。其他人可以想出一个更好的例子。它基本上只是一种消息传递方式,而不对消息提供者或接收者是否存在做出任何假设。
Have you thought of pubsub? Something as simple as.
or drop the jQuery dependency
Both amplify.subscribe and Backbone.Events have specific objects for this. You may even find other libraries with similar objects. There are even libraries PubSub.js for this.
Example:
In general
pub
istrigger
andsub
isbind
. In this particular example we have two independent plugins. They don't know whether they are on the same page or talking at all. But since the sorting "breaks" the paging plugin on our table we have a subscription on the sorting "event" to fix our paging.Someone else can come up with a better example. It's basically just a way of message passing without making any assumptions about whether either the message giver or receiver exists.
查看jquery源代码。当您在 jQuery 上触发事件时,它会检查有效节点
,然后检查实际 dom 对象上的有效处理程序,
我认为真正的问题是 $('*') 选择器的使用。尝试针对您的问题建议的另一种解决方案
Looking at jquery source code. When you trigger an event on jQuery it check for a valid node
And later check for a valid handler on the actual dom object
I think that the real problem is the use of $('*') selector. Try another of the suggested solutions to your problem