There are times when I need to write a local javascript function (without needing a round trip to the server) and I’d like to use RJS rather than writing the function in pure javascript. Why would I want to use RJS?
- The syntax is clean and it’s often less code than pure javscript.
- When writing this function, I can mix in powerful Ruby constructs.
- It’s consistent with the other RJS in the project.
- I automatically get the function wrapped up in a CDATA tag.
- I automatically get exceptions handled by giving me an alert of the problem.
- It’s easy to conditionally exclude some of the javascript.
- My rails views look cleaner.
Here’s an example from a rails view (new.erb):
1 2 3 4 5 6 |
|
So where’d this define_js_function method come from? I added it to ApplicationHelper. Here it is:
1 2 3 4 5 6 7 8 |
|
When the view is rendered in the browser, the following javascript gets generated:
1 2 3 4 5 6 7 8 9 10 11 |
|
If the javascript function you’re creating takes no arguments, then you simply pass a symbol to define_js_function to specify the function name. If your function takes arguments, then you can pass in a string which contains those arguments like so:
1 2 3 4 |
|