在 document.ready 上运行 CoffeeScript 类
我有
class Main
test:->
alert "yay!"
coffeescript,我想在我的index.html 中运行它,
<script>
$(function(){
//and obv Main.test(); doesn't work
});
</script>
网站上有一个注释,它说它不起作用。但我找不到如何让它发挥作用。有什么想法吗?我需要找出 Coffeescript 闭包包装器是什么。
或者 Coffeescript 是否在 document.ready 之后执行?
谢谢!
i have
class Main
test:->
alert "yay!"
in coffeescript, and i want to run that inside my index.html
<script>
$(function(){
//and obv Main.test(); doesn't work
});
</script>
there is a note of this on the website, it says it wouldn't work. But I couldn't find how to make it work. any ideas? i need to find out what coffeescript closure wrapper is.
or does coffeescript execute after document.ready anyway?
thx!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
要在 document.ready 之后执行 Coffeescript,您可以像这样使用 jQuery:
所做的就是运行 jQuery(function () {callback... }),就像此链接的第三部分一样:
http://api.jquery.com/jQuery/
基本上是这样说的:
jQuery(callback) 返回:jQuery
描述:绑定一个在 DOM 加载完成时执行的函数。
我在文档之外声明所有类等,然后调用 init 函数以使其在适当的时间运行。
我希望这有帮助!
To execute Coffeescript after document.ready you can use jQuery like this:
What that is doing is running jQuery(function () { callback... }) like the 3rd section at this link:
http://api.jquery.com/jQuery/
Which basically says this:
jQuery( callback ) Returns: jQuery
Description: Binds a function to be executed when the DOM has finished loading.
I declare all my classes, etc outside of document ready and then call an init function to get it running at the appropriate time.
I hope that helps!
尝试使用
class @Main
代替。对吧。应为
new Main().test()
或Main::test()
。假设您通过 extras/coffee-script.js 执行它 并使用 jQuery,是的。
Try
class @Main
instead.Right. Should be
new Main().test()
orMain::test()
.Assuming that you're executing it via extras/coffee-script.js and using jQuery, yes.
Coffeescript 将您的代码包装在函数调用中,这样您就不会意外覆盖全局变量。
如果您希望任何变量、函数或类成为全局变量(以便其他文件可以访问它们),则需要通过将它们附加到
this
或window
。这编译为:
Coffeescript wraps your code in a function call so you can't accidentally overwrite global variables.
If you want any variables, functions or classes to be global (so they can be accessed by other files), you need to explicitly make them global by attaching them to
this
orwindow
.This compiles to:
我以前也遇到过这个问题。首先,由于您正在定义一个类,因此您需要实例化它。然后您可以在实例上调用
test
函数:但是,您可能已经注意到浏览器找不到您的
Main
类。这是因为,当编译 CoffeeScript 时,它会在类定义周围包装一个自执行函数,以防止Main
被全局访问。如果你想让它全局可访问,你可以在它前面加上 window: 前缀,或者在定义它之后赋值:
I've run into this issue before as well. First of all, since you are defining a class, you need to instantiate it. Then you can call you
test
function on the instance:However, you might have noticed that the browser can't find your
Main
class. This is because when the CoffeeScript is compiled, it wraps a self-executing function around your class definition in order to preventMain
from being globally accessible. If you want to make it globally accessible, you can prefix it with window:or assign it after defining it: