.js.erb VS .js

后端 未结 3 1686
梦如初夏
梦如初夏 2020-12-01 00:46

What is the advantage to putting you javascript for your rails app into a .js.erb file instead of just throwing it in your application.js file? I have a create button for bu

3条回答
  •  执笔经年
    2020-12-01 01:18

    If I may contribute to the answer with my few cents...

    The answer to your question is really simple :

    • A file ending with *.js.erb allows your file to be interpreted by ruby. (So you will be able to use rails helpers)

    • A file ending with *.js is a pure javascript.

    You will never get a *.js file to work if you place any ruby code inside like:

    $(function () {
      new Highcharts.Chart({
        chart: { renderTo: 'orders_chart' },
        title: { text: <%= gon.my_title_of_the_day.to_json %> },
      });
    })
    

    The part <%= gon.my_title_of_the_day.to_json %> will just generate an error because javascript knows nothing about ruby.

    In order your *.js file works, you will have to statically change it every time the day changes:

    $(function () {
      new Highcharts.Chart({
        chart: { renderTo: 'orders_chart' },
        title: { text: 'Monday' },
      });
    })
    

    N.B. : If you use a *.js.erb, you will need in addition the "Gon" gem to pass data from your controller to JS though.

    Now for your underlying question "why is my javascript code not working '" I can't answer because I'm no javascript expert and this is another story... ;-)

提交回复
热议问题