Using Rails 3.1, where do you put your “page specific” JavaScript code?

前端 未结 29 1820
一生所求
一生所求 2020-11-22 11:08

To my understanding, all of your JavaScript gets merged into 1 file. Rails does this by default when it adds //= require_tree . to the bottom of your appl

29条回答
  •  渐次进展
    2020-11-22 11:31

    Though you have several answers here, I think your edit is probably the best bet. A design pattern that we use in our team that we got from Gitlab is the Dispatcher pattern. It does something similar to what you're talking about, however the page name is set in the body tag by rails. For example, in your layout file, just include something like (in HAML):

    %body{'data-page' => "#{controller}:#{action}" }
    

    Then only have one closure and a switch statement in your dispatcher.js.coffee file in your javascripts folder like so:

    $ ->
      new Dispatcher()
    
    class Dispatcher
      constructor: ->
        page = $('body').attr('data-page')
        switch page
          when 'products:index'
            new Products() 
          when 'users:login'
            new Login()
    

    All you need to do in the individual files (say products.js.coffee or login.js.coffee for example) is enclose them in a class and then globalize that class symbol so you can access it in the dispatcher:

    class Products
      constructor: ->
        #do stuff
    @Products = Products
    

    Gitlab has several examples of this that you might want to poke around with in case you're curious :)

提交回复
热议问题