What is a good way to separate concerns with CoffeeScript and Ruby on Rail's asset pipeline? -
tldr:
what can combine multiple coffeescript files 1 js file, in ror, under same anonymous function block?
long version:
i have few cs files loaded part of ror web app. i'm wondering: way separate concerns coffeescripts , ruby on rail 3.1's asset pipeline?
let's use following example code:
main.js.coffee
window.myapp = {} # escape coffeescript anonymous function block # (i anonymous function block because protects other my_global_setting = "world!" $.click "#my_button" myapp.sayhello # (i use goog.bind here instead of using myapp. suggestions? fat arrow?)
hello.js.coffee
myapp.sayhello = sayhello () -> docomplicatedstuff() alert("hello #{ my_global_setting }")
complicated.js.coffee
docomplicatedstuff = () -> # complicated algorithm, example true
i have assets directory structured following:
assets/ application.js application/ # javascript gets used main application secondary_page.js secondary_page/ complicated.js.coffee hello.js.coffee main.js.coffee
secondary.js
//= require secondary_page/main.js.coffee //= require secondary_page/complicated.js.coffee //= require secondary_page/hello.js.coffee
i used compile files coffeescript part of build process, want use asset pipeline instead. i'm drinking ror 3.1 kool-aid! haha, though, asset pipeline looks awesome.
the problem i'm experiencing secondary.js looks following:
(function() { // main.js ).call(this); (function() { // complicated.js ).call(this); (function() { // hello.js ).call(this);
this prevents local variables being shared amongst entire code. my_global_setting , docomplicatedstuff aren't available sayhello.
so... should do? can't think of way without introducing own custom compilation step again.
this common question rails developers starting use coffeescript. see, example:
- "can't find variable" error rails 3.1 , coffeescript
- functions in controller.js.coffee
- how can use option "--bare" in rails 3.1 coffeescript?
solutions abound. simplest preface variable declarations want visible outside of particular file @
, since this
point window
in outermost context of each file, , x
points window.x
when no local x
defined.
Comments
Post a Comment