简体   繁体   中英

What's the best way to split up my Javascript or Coffeescript in a Rails app?

Let's say I have a rails app with a resource - User. I have javascript that should be available for any page that is served. I have javascript that should be available for any page that is served under User. And I have javascript that should be available for each specific action under User. In Rails 3.1 and higher, is there an easy way to make sure that my Javascript is only available to the pages that require it? What about coffeescript?

I think the linked item from Bob is relevant (there's a comment relating to trade-off of performance to number of files loaded), but I saw the question as being more about name spacing, scoping and structure.

To specifically answer the question (and assuming you're using jQuery), consider the following CoffeeScript:

$ ->
  doSomething()
  doSomethingElse("#some-element")

doSomething = ->
  alert("I'm doing something")

doSomethingElse  = (selector) ->
  alert("I'm hiding something")
  $(selector).hide()

The CoffeeScript compiler will wrap all of this within an anonymous function, and thus will only be available within a context from which the page is loaded (a script tag, or a controller-specific file, or the application.js for global visibility).

There are a couple of models to consider. A straightforward one is to follow the pattern of having "things" that are specific to a model, and those that are generally useful (global). So if I want a javascript function that's specific to User, then it goes in app/assets/javascripts/users.js.coffee , otherwise it needs to be global (in application.js.coffee ).

A much more complete and complex solution is suggested by the rails-backbone gem, which has generators that create CoffeeScript models, views, templates and routers that replace a lot of what we would get with regular rails generate scaffold foo -- the same kinds of CRUD operations are done in an entirely different way, and the templates (embedded javascript) in particular are quite similar to ERB templates. This is more of a leap of faith, for me.

Whether in an application-wide file, or a controller-specific one or ones, in either case, the Asset Pipeline will glom all of the code together and send it all to the user (assuming you retain the default configuration), but that's a separate topic.

Not sure if this answers the question, you had, but I think it's important to distinguish between the delivery of assets, which Asset Pipeline does, and the execution of javascript, which is a matter of scoping, something CoffeeScript does a very nice job of, and which backbone.js takes even further.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM