JS 原型:避免事件处理程序多次绑定到同一个对象
因此,对于新的 ajax 事物,我们必须在每次进行 ajax 调用时重新初始化 Javascript 事件处理程序,因为 ajax 调用可能会导致整个页面的大量重绘,从而导致未初始化的对象。
看看这个 jsfiddle: Javascript 事件处理程序多次添加到同一个对象
这就是我所拥有的,它似乎有效,但是因为它将与我们拥有的一切一起使用:我想确保它是正确的解决方案。 例如,全局定义的变量
MyCompany.field.bindedOnfocusSelector = MyCompany.field._focusEventHandler.bindAsEventListener(MyCompany.field);
感觉不对。而且它缺乏传递更多函数参数的可能性。
正如另一张海报建议的原型 $(smth).on(event)
我在让它工作时遇到了问题 - 我记得跨浏览器方面的问题(例如,在 IE 8 上,在 Firefox 中工作的东西不起作用)即使在这个更简单的示例中 jsFiddle 的 on('focus') 问题:
So with the new ajax things we have to reinitialize our Javascript event handlers every time an ajax call is made, since an ajax call can result in pretty heavy redrawing of the whole page resulting in uninitialized objects.
Have a look at this jsfiddle:
Javascript eventhandler added multiple times to the same object
This is what I have and it seems to work, but since it is going to be used with everything we have: I wanna make sure that it is the right solution.
E.g. the global defined variable
MyCompany.field.bindedOnfocusSelector = MyCompany.field._focusEventHandler.bindAsEventListener(MyCompany.field);
just feels wrong. And it lacks the possibility to hand more function arguments.
As another poster suggested the prototype $(smth).on(event)
I have problems to get it working - I remember problems crossbrowser wise (e.g. on IE 8 things didn't work which worked in Firefox) and even in this simpler example jsFiddle problem with on('focus'):
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您注册一个ajax响应程序怎么样,并在请求完成后添加方法
更新
好吧,考虑到您的评论,观察整个页面即
body
并确定如何如果发生输入事件,例如:我认为这会对您有所帮助,因为您只需添加一个观察者,并且永远不需要删除它,您的所有逻辑都可以包含在内。
PS:请注意
Event.on
仅在原型 1.7 中可用UPDATE
好吧,如果你只是检查点击,键盘现在无法工作,但我认为这是一个可行的解决方案
更新的Fiddle
How about you register an ajax responder, and add the methods after a request has completed
UPDATE
Ok, taking into consideration your comment, how about observing the whole page i.e.
body
and determining if a input event occurred, ex:I think this will help you as you only add one observer, and never need to remove it, all your logic can be contained.
PS: note that
Event.on
is only available in prototype 1.7UPDATE
ok, what if you just check the click, keyboard won't work now though but i think this is a viable solution
Updated Fiddle