jQuery 绑定自定义事件时触发代码
JQuery 对自定义事件有很好的支持 - .bind("foo", function(e)...
。但是,如果触发事件的机制尚未准备好并且必须仅在那些绑定了事件的元素?
例如,我想要一个在元素滚动到视口时触发的 scrollin
事件,为此,我需要 onscroll
。检查所有元素并trigger
scrollin
在那些在视口之外但现在在视口内的东西上,这是不可接受的,
例如,其中一个插件。检查“private”$.cache
中的所有元素,并仅检查那些绑定了 scrollin
事件的元素,
但这也很丑陋,我需要的是一个额外的回调。对于绑定负责滚动管理的事件(除了用于处理的回调之外),即将元素放入某些 elementsCheckOnScroll
缓存数组中。
我正在寻找类似的东西:
$.delegateBind("scrollin", function(jqSelection) { ... });
element.bind("scrollin", function(e) {..}); //Calls ^ after internal bind management
编辑:这将是很好的API!
$.bind("bind", function(onWhat) { ... })
:-)
JQuery has great support for custom events - .bind("foo", function(e)...
. However what if the mechanic of triggering the event is not ready yet and has to be constructed only on those elements that have the event bound on?
For example I want a scrollin
event that gets fired when an element is scrolled into a viewport. To do this, I would onscroll
have to check all the elements and trigger
scrollin
on those that were outside the viewport and now are inside. This is not acceptable.
There are some tricks to speed it up. For example one of the plugins for this checks all the elements in "private" $.cache
and does the checking only on those that have scrollin
event bound.
But that's also ugly. What I need is an additional callback for the binding of the event (additional to the callback for handling) that would take care of the scroll management, that is to put the element(s) into some elementsCheckOnScrol
cache array.
I'm looking for something like:
$.delegateBind("scrollin", function(jqSelection) { ... });
element.bind("scrollin", function(e) {..}); //Calls ^ after internal bind management
Edit: This would be nice api!
$.bind("bind", function(onWhat) { ... })
:-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我没有误解您的意思,您可以像这样修补
bind
方法:它的作用是检查
scrollin
是否被绑定,如果是,则调用您的委托功能。之后,它只是调用原始的绑定函数,该函数会像平常一样执行所有 jQuery 操作。添加此代码后,您可以像这样使用它: http://jsfiddle.net/pimvdb/g4k2G/< /a>.
请注意,这不支持将对象文字传递给
.bind
(仅(name, func)
),但您也可以实现它。If I'm not misunderstanding you, you could patch the
bind
method like this:What it does is checking whether a
scrollin
is being bound, and if so, calls your delegate function. After that it simply calls the original bind function which does all jQuery things like it does regularly.After having added this code, you could use it like this: http://jsfiddle.net/pimvdb/g4k2G/.
Note that this does not support object literals being passed to
.bind
(only(name, func)
), but you could implement that as well.我发现了一个
$.event.special
API,但我不知道它的公开程度。它不在文档中,并且之前至少已更改过一次。 http://benalman.com/news/2010/03/jquery-special-事件/I found an
$.event.special
API, but I don't know "how much" public it is. It is not in the docs and has been changed at least once before. http://benalman.com/news/2010/03/jquery-special-events/