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

后端 未结 2 891
死守一世寂寞
死守一世寂寞 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: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.

提交回复
热议问题