jQuery 中的取消绑定/绑定与委托:哪个是最佳解决方案?
我有 jQuery 代码,用于处理动态添加到页面的元素的取消绑定和绑定事件处理程序。该代码有一个包装函数,该函数将现有处理程序与具有给定 id 前缀的元素解除绑定,然后绑定事件处理程序,以便任何现有元素都具有该处理程序,并且任何新添加的具有相同 id 前缀的元素也可以获得该处理程序。显然,这会对添加新元素时已经存在的具有 id 前缀的元素进行额外的解除绑定/绑定。取消绑定是为了防止现有元素获得分配给它们的多个相同类型的处理程序。
自从最初编写这段代码以来,我已经了解了 jQuery 委托函数,该函数似乎与我上面所做的完全一样。
委托函数会比我做得更好吗?这样我就值得花时间重写当前的工作代码来利用它吗?我所说的更好是指性能、内存使用或其他一些衡量标准。
I have jQuery code that handles unbinding and binding event handlers to elements that are dynamically added to the page. The code has a wrapper function that unbinds existing handlers from elements with a given id prefix, and then binds the event handlers so that any existing elements have the handler and any newly added elements of the same id prefix get it as well. Obviously this does extra unbinding/binding on elements with the id prefix that already exist when a new element is added. The unbind is done to prevent existing elements getting multiple handlers of the same type assigned to them.
Since originally writing this code, I have learned about the jQuery delegate function that essential seems to do exactly what I have done above.
Would the delegate function do what I have done significantly better, such that it would be worth my time to rewrite my current working code to take advantage of it? By better I mean performance, memory use, or some other measure.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您使用
.delegate()
时,您应该选择一个祖先元素,该元素将作为指定后代上的事件的侦听器。这很棒,因为从一开始您就绑定了一个侦听器,该侦听器应该或多或少“永久”在您的页面上,无论从其后代树中添加或删除了多少有效目标。这当然比动态页面的
.click
更好,并且比在元素上使用一系列.bind
和.unbind
更好。添加或删除。但是,它可能等同于使用
.bind()
来选择侦听指定后代点击的祖先元素。我对.bind()
不太熟悉,无法确定性能优势。--
顺便说一句与您的问题没有具体关系,它是一个比
.live()
性能更好的函数,因此如果您想使用.live()
> 我强烈推荐.delegate()
作为更好的选择。When you use
.delegate()
, you are expected to choose an ancestor element that will be the listener for events on designated descendents. Which is great because right from the beginning you are binding a listener that should be more or less "permanent" on your page, regardless of how many valid targets are added or removed from its descendent tree.This is certainly better than
.click
for dynamic pages, and is better than using a series of.bind
and.unbind
on elements as they get added or removed.However, it might be equal to using
.bind()
in a way that chooses an ancestor element that listens for clicks on designated descendents. I'm not familiar enough with.bind()
to say for sure about performance benefits.--
As an aside not specifically related to your question, it IS a better-performing function than
.live()
, so if you are ever tempted to use.live()
I would strongly recommend.delegate()
as a better option.