Coffeescript wraps your code into a wrapper like
(function() {
/* your code */
}).call(this);
Here, this
means window
. So, 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
Just do
window.publicObject.someMethod()
. This avoids the whole variablethis
scope issue. You can usethis
andwindow
interchangeably in the top level scope of you CS code, but once you get inside functions, you'll need to usewindow
. I suggest usingwindow
all the time as its A) clearer and B) sidesteps the wholethis
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.
The wrapper doesn't hide
document
, which is a global because it's attached towindow
. Unless you've declared a variable nameddocument
within your.coffee
file (by writingdocument = ...
),document
will be accessible fromsomeMethod
. Try addingconsole.log document
to the top ofsomeMethod
to check for yourself.So there must be something else going on. What exactly is the error message you get when
someMethod
is called?