简体   繁体   中英

How to fire CoffeeScript/Javascript after user presses back button

Different parts of the UI on my Rails 4 application rely on a dynamically populated select controls, where the option selected in the first select determines the options available in the second select. The script that sets the options of the second select runs when the select's onChange event is fired.

Everything works fine, until the user clicks the browser's back button and returns to the form that contains the two select controls. The first select retains the user's selection, but the second select (which is dynamically populated by the script) reverts to default options.

Browsers don't seem to fire any event at all when the user uses the back button, so there doesn't appear to be anything for me to hang my script on. How can I get my script to run after the user presses the back button?

What are my alternatives if I can't get the actual script to run? Do I have to ditch dynamic selects in favor of a single, massive select that lists all options in one control?

This is an inelegant, but expedient solution:

Rather than recreating my own session history mechanism, I just added a javascript_tag to my form which included a copy of the script which runs on page load (including when the user hits the back button, whereas the script in my assets folder only ran when the page was newly loaded).

This solution isn't DRY by any means, but it works in this limited circumstance.

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