访问coffeescript的默认包装器中的文档 [英] Accessing document within coffeescript's default wrapper

查看:133
本文介绍了访问coffeescript的默认包装器中的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Coffeescript会将您的代码封装为

Coffeescript wraps your code into a wrapper like

(function() { 
/* your code */
}).call(this);

在这里, this 表示 window 。所以,为了创建一个公共接口,我做一些像

Here, this means window. So, to create a public interface I do something like

this.publicObject =
  someMethod: ->
    document.getElementById("button1").innerHTML = "Changed!"

然后,我可以在调用我的.js文件的HTML文档中注册一个回调,例如< span onclick =publicObject.someMethod();>点击< / span>

I can then register a callback in the HTML document invoking my .js file with something like <span onclick="publicObject.someMethod();">Click</span>.

但是,如果我想从.coffee文件中调用someMethod()在文档准备就绪,我认为 answer + comments下面)?如果我只是跟上面的代码

However, what if I wanted to call someMethod from the .coffee file (to be called on document ready, I think See accepted answer + comments below)? If I just follow the above code up with

publicObject.someMethod()

由于上下文问题,似乎文档对象在someMethod中不可访问。 我如何从我的.coffee文件调用 publicObject.someMethod(),并让它识别 document

it seems like the document object is not accessible within someMethod due to context issues. How can I call publicObject.someMethod() from my .coffee file and have it recognize document?

注意: apply() call $ c> trickery是好的,但我不想摆脱包装,如果可能的话。如果你关心,我使用以下来编译我的脚本:

Note: apply() and call() trickery is OK, but I don't want to get rid of the wrapper, if possible. If you care, I use the following to compile my script:

coffee -j -p -c coffee/*.coffee > www/app.js


推荐答案

文档,这是一个全局因为它附加到窗口。除非你在你的 .coffee 文件中声明了一个名为的变量(通过写 document = ... ),文档将可从 someMethod 访问。尝试在 someMethod 的顶部添加 console.log文档以检查自己。

The wrapper doesn't hide document, which is a global because it's attached to window. Unless you've declared a variable named document within your .coffee file (by writing document = ...), document will be accessible from someMethod. Try adding console.log document to the top of someMethod to check for yourself.

所以必须有别的东西。当调用 someMethod 时,得到的错误消息是什么?

So there must be something else going on. What exactly is the error message you get when someMethod is called?

这篇关于访问coffeescript的默认包装器中的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆