how should I include a coffeescript file on only one page?

后端 未结 2 887
死守一世寂寞
死守一世寂寞 2021-02-05 05:06

Edit: a year later if I was going to do this again I\'d do it with curl.js instead of Rails asset pipeline.

Related: Best way to add page specific javascript in a Rails

相关标签:
2条回答
  • 2021-02-05 05:15

    Rather than only including the file on one page, you might want to just use logic that's conditional on the page markup. See my answer to a related question. That way, your users don't have to make an additional <script> request for the particular page.

    If there's a lot of logic specific to that page (say, 10K+ minified), then yes, split it out. As you suggested in the edit to your question: Rather than doing require_tree . at the root of your javascripts directory, instead create a sub-directory called global and change the top of application.js from

    require_tree .
    

    to

    require_tree global
    

    Then put your page-specific CoffeeScript file in the root javascripts directory, and point to it with a javascript_include_tag call in that page's template.

    0 讨论(0)
  • 2021-02-05 05:17

    Here's the approach I use to make controller/view specific Coffee:

    application.html.haml:

    %body{ :data => { :controller => params[:controller], :action => params[:action]} }
    

    alt. application.html.erb

    <%= content_tag(:body, :data => { :controller => params[:controller], :action => params[:action] }) do %>
      ...
    <% end %>
    

    application.js.coffee:

    $(document).ready ->
      load_javascript($("body").data('controller'),$("body").data('action'))
    
    load_javascript = (controller,action) ->
      $.event.trigger "#{controller}.load"
      $.event.trigger "#{action}_#{controller}.load"
    

    users.js.coffee

    $(document).bind 'edit_users.load', (e,obj) =>
      # fire on edit users controller action
    
    $(document).bind 'show_users.load', (e,obj) =>
      # fire on show users controller action
    
    $(document).bind 'users.load', (e,obj) =>
      # fire on all users controller actions
    

    Sidenote:

    This works great with PJAX as well as you can pass the controller/action names with the response header on PJAX requests and just fire these js functions based on that.

    EDIT (2014/03/04): This solution still works when using turbolinks.js.

    0 讨论(0)
提交回复
热议问题