I recently started using coffeescript and was curious what is the "right" way to expose an object that I create with Coffeescript to other javascript pages. Because of coffeescripts wrapping functionality, is it acceptable behavior to call window.coffeeObject = externalObject
.
Example
example.coffee
externalObject =
method1: -> 'Return value'
method2: -> 'Return method2'
window.myApi = externalObject
example.js -- compiled from example.coffee
(function() {
var externalObject;
externalObject = {
method1: function() {
return 'Return value';
},
method2: function() {
return 'Return method2';
}
};
window.myApi = externalObject;
}).call(this);
other.js
alert(myApi.method1()) // Should return "Return value"
Yep that's correct. Alternatively you can use define
@myApi = { foo: -> }
becausethis
iswindow
in the root context of the file.You can simplify the syntax further, for example if you had 2 internal functions
example.coffee
example.js
The
@
will bewindow
within the main scope of the file.Then call from elsewhere by
window.myApi.myFunction()
If you wanted to map the external function names to the same internal names, if you don't specify
key : value
pairs, it will just use the string value as the key by default.example.coffee
example.js