.js.erb VS .js

后端 未结 3 1693
梦如初夏
梦如初夏 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:35

    .js.erb files are for controller actions, such as create, when you want javascript to be executed when the action completes. For example, when you want to submit a form via ajax and want display an alert when everything is done, you would put the

    $('#business_submit').click(...)
    

    in your application.js or *.html.erb, and your create.js.erb could look like this:

    alert('New object id: ' + <%= new_object.id %>);
    

    This way, the javascript that is getting returned to the browser can be first rendered by Erb, allowing you to insert custom strings/variables/etc just like you can in .html.erb templates.

提交回复
热议问题