开发者

Accessing document within coffeescript's default wrapper

Coffeescript wraps your code into a wrapper like

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

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

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

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

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

publicObject.someMethod()

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?

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


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.

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


Just do window.publicObject.someMethod(). This avoids the whole variable this scope issue. You can use this and window interchangeably in the top level scope of you CS code, but once you get inside functions, you'll need to use window. I suggest using window all the time as its A) clearer and B) sidesteps the whole this issue which has caused countless hours of head scratching.

Also, this is the namespace pattern I use. I create 1 top-level global object and hang everything off of that neatly. It starts like this.

OT = window.OT = {} #root of the public API namespace
OT.someNestedPublicObj = {}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜