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

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

    For the page-specific js you can use Garber-Irish solution.

    So your Rails javascripts folder might look like this for two controllers - cars and users:

    javascripts/
    ├── application.js
    ├── init.js
    ├── markup_based_js_execution
    ├── cars
    │   ├── init .js
    │   ├── index.js
    │   └── ...
    └── users
        └── ...
    

    And javascripts will look like this:

    // application.js
    
    //= 
    //= require init.js
    //= require_tree cars
    //= require_tree users
    

    // init.js
    
    SITENAME = new Object();
    SITENAME.cars = new Object;
    SITENAME.users = new Object;
    
    SITENAME.common.init = function (){
      // Your js code for all pages here
    }
    

    // cars/init.js
    
    SITENAME.cars.init = function (){
      // Your js code for the cars controller here
    }
    

    // cars/index.js
    
    SITENAME.cars.index = function (){
      // Your js code for the index method of the cars controller
    }
    

    and markup_based_js_execution will contain code for UTIL object, and on DOM-ready UTIL.init execution.

    And don't forget to put this to your layout file:

    
    

    I also think that it is better to use classes instead of data-* attributes, for the better page-specific css. As Jason Garber have mentioned: page-specific CSS selectors can get really awkward (when you use data-*attributes)

    I hope this will help you.

提交回复
热议问题