views:

74

answers:

2

I have a form with an ever-growing amount of associated javascript. At present this javascript lives in my form view which is fine, but it's getting larger and starting to overwhelm the form making it difficult to work on the form.

I want to put this in a separate file in my /public/javascripts directory but a lot of the javascript is generated by embedded ruby. This embedded ruby is ignored and passed through to the browser if I just put the code here.

What is the best way (if any) of having this embedded ruby executed and the javascript being generated in the same way as if it were in my view?

+1  A: 

You can create RJS templates and group your Javascript code in the RJS files. Refer: http://www.codyfauser.com/2005/11/20/rails-rjs-templates

Shripad K
Hmm, that seems a bit more for AJAX type stuff? Is that correct? Anyway I went with user211722's idea. Thanks though
brad
+1  A: 

You can create dynamic erb templates for javascript, but they don't go in the public/javascripts directory.

I suggest you move the javascript into a partial. Create a file named _form_js.html.erb and put the content of your script tag there. Then <%= render :partial => 'form_js' %> from your view.

As a side note, it is likely that you would be better off using completely static javascript that identifies elements of the form by their class/id and reacts to this, rather than using custom javascript for each element.

Daniel Heath
That works perfectly. Thanks. The only issue I have is that the source code of my page contains all of my javascript when I open it up in the browser. Not a big deal but I do like my pages to look nice and minimal if someone takes a peek behind the scenes.
brad
That is the preferred way to do it, yeah.I find the best solution for that is to give the elements you need to work with classes, and then include a completely static javascript file that uses jQuery or similar to identify which elements should be modified.
Daniel Heath