简体   繁体   中英

Rails: How to run javascript when the controller render action

For the sake of argument, we have " new product " form.

I use some javascript libraries for html form elements (eg icheck, select2, wysihtml5). These form elements needed to be run with their associated js library functions to show properly (eg $(".checkbox").iCheck({...} ) ) before rendering the HTML page.

If there is validation errors on submitting the form, Rails will render action " new " to reshow " new product " form with errors (exactly in the " Create " method in " ProductsController ").

The problem is Rails will not execute associated javascript files (eg products.js.coffee) again in this situation. Then, the javascript based html form elements cannot be shown properly as they should be (because $(".checkbox").iCheck({...}) does not get executed).

How can I resolve this problem?

This could be a turbolinks problem. Look at the jquery-turbolinks gem, or try the following:

ready = ->

  ...your coffeescript goes here...

$(document).ready(ready)
$(document).on('page:load', ready)

You could also try and disable turbolinks to see if it is, in fact, the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM