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