我有
class Main
test:->
alert "yay!"
Run Code Online (Sandbox Code Playgroud)
在coffeescript中,我想在index.html中运行它
<script>
$(function(){
//and obv Main.test(); doesn't work
});
</script>
Run Code Online (Sandbox Code Playgroud)
在网站上有一个这样的说明,它说它不起作用.但我找不到如何使它工作.有任何想法吗?我需要找出什么是coffeescript封装包装.
或者coffeescript是否在document.ready之后执行?
谢谢!
Bra*_*don 26
要在document.ready之后执行Coffeescript,你可以像这样使用jQuery:
$ ->
# Put your function code here
init()
Run Code Online (Sandbox Code Playgroud)
正在做的是运行jQuery(function(){callback ...}),就像这个链接的第3部分一样:http: //api.jquery.com/jQuery/
基本上这说:
jQuery(callback)返回:jQuery描述:绑定DOM完成加载时要执行的函数.
我在文档之外声明我的所有类等,然后调用init函数以使其在适当的时间运行.
我希望有所帮助!
mat*_*tyr 24
class Main
试试吧class @Main.
obv Main.test(); 不起作用
对.应该是new Main().test()或Main::test().
coffeescript会在document.ready之后执行吗?
假设您通过extras/coffee-script.js并使用jQuery 执行它,是的.
Coffeescript将您的代码包装在函数调用中,因此您不会意外地覆盖全局变量.
如果您希望任何变量,函数或类是全局的(因此可以通过其他文件访问它们),您需要通过将它们附加到this或显式使它们全局化window.
# Stays within the function scope, so you can't access it outside the file
myNotGlobalFunction -> return
# Attaches it to `this` aka `window`, so can be accessed globally
this.myGlobalFunction -> return
# A shortcut using @ which is an alias to `this.`
@myOtherGlobalFunction -> return
Run Code Online (Sandbox Code Playgroud)
这编译为:
(function() {
myNotGlobalFunction(function() {
return;
});
this.myGlobalFunction(function() {
return;
});
this.myOtherGlobalFunction(function() {
return;
});
}).call(this);
Run Code Online (Sandbox Code Playgroud)