如何适时设置JS事件
在我的rails(3.0.x,仍然带有原型)附带的rails.js中,我看到以下结构:
(function() {
// ...
document.on("click", ...
})();
将整个代码包装在匿名函数中到底完成了什么?这是延迟代码直到 dom 加载还是仅加载文档对象的有效方法吗?
在我的项目中,我目前在 Event.observe(document, 'dom:loaded', function() { ... }
块内有很多设置代码。我想知道,我是否应该当我重构代码时采用上面的模式。
In the rails.js that came with my rails (3.0.x, still with prototype), I see the following structure:
(function() {
// ...
document.on("click", ...
})();
What exactly is accomplished with the wrapping of the whole code in the anonymous function? Is this a valid way to delay the code until the dom has loaded or only the document object?
In my project, I currently have a lot of setup code inside a Event.observe(document, 'dom:loaded', function() { ... }
block. I was wondering, if I should adopt the pattern above when I refactor my code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您偶然发现了模块模式。它很有用,因为立即调用的函数内的变量是本地的,不会污染全局命名空间。
请注意,由于立即调用函数(在最后的
()
位中),所以时间上没有差异You have stumbled across the module pattern. It is useful because variables inside the immediately invoked function are local and don't pollute the global namespace.
Not ethat there is no difference in timeing since the function is immediately invoked (in the final
()
bit)自调用匿名函数会立即触发里面的内容,与延迟代码无关。
为了让里面的代码块在 DOM 准备好后执行,你必须有 DOMready 监听器。我猜你提到的代码
Event.observe(document, 'dom:loaded', function() { ... }
就是这样的代码。The self-invoking anonymous function will trigger what is inside immediately, which has nothing to do with delaying the code.
To make the code block inside be executed after the DOM is ready, you have to have DOMready listener. I guess the code you mentioned
Event.observe(document, 'dom:loaded', function() { ... }
is the one.