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

前端 未结 29 1846
一生所求
一生所求 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:34

    Following the lead from Ryan, here's what I have done-

    application.js.coffee

    $ ->
        view_method_name = $("body").data("view") + "_onload"
        eval("#{view_method_name}()") if eval("typeof #{view_method_name} == 'function'")
        view_action_method_name = $("body").data("view") + "_"+$("body").data("action")+"_onload"
        eval("#{view_action_method_name}()") if eval("typeof #{view_action_method_name} == 'function'")
    

    users.js.coffee (controller specific coffeescript,e.g controller:users, action:dashboard)

    window.users_dashboard_onload = () ->
        alert("controller action called")
    window.users_onload = () ->
        alert("controller called")
    

    application.html.haml

    %body{:data=>{:view=>controller.controller_name, :action=>controller.action_name}}
    
    0 讨论(0)
  • 2020-11-22 11:35

    I agree with your answer, to check if that selector is there, use:

    if ($(selector).length) {
        // Put the function that does not need to be executed every page
    }
    

    (didn't see anyone add the actual solution)

    0 讨论(0)
  • 2020-11-22 11:35

    I did it previously using this method: http://theflyingdeveloper.com/controller-specific-assets-with-rails-4/ . Super-easy, relies on controllers to select the proper js to load.

    0 讨论(0)
  • 2020-11-22 11:36

    You can add this line in your layout file (e.g. application.html.erb) to automatically load the controller specific javascript file (the one that was created when you generated the controller):

    <%= javascript_include_tag params[:controller] %>
    

    You also could add a line to automatically load a script file in a per-action basis.

    <%= javascript_include_tag params[:controller] + "/" + params[:action] %>
    

    Just put your page scripts into a subdirectoriy named after the controller name. In these files you could include other scripts using =require. It would be nice to create a helper to include the file only if it exists, to avoid a 404 fail in the browser.

    0 讨论(0)
  • 2020-11-22 11:37

    Maybe you will find pluggable_js gem as suitable solution.

    0 讨论(0)
  • 2020-11-22 11:37

    I haven't tried this out, but it looks like the following is true:

    • if you have a content_for that is javascript (e.g. with real javascript within it), sprockets would not know about it and thus this would work the same way as it does now.

    • if you want to exclude a file from the big bundle of javascript, you would go into config/sprockets.yml file and modify the source_files accordingly. Then, you would just include any of the files that you excluded where needed.

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