views:

40

answers:

2

Hi.

My main intention is to keep the functionality independent form the Javascript, to have it gracefully degradable. Maybe I am trying to go where I want the wrong way but the main idea is:

  • there are some jQuery UI tabs and when the user presses a link, a new tab is added corresponding to that action
$("#tabs").tabs('add', "/groups", "My Groups");
  • the controller identifies the AJAX request and renders only the partial for that tab
if request.xhr?
  render  :partial => "index_tab"
end
  • at this point I would like the Javascript file associated with the /groups/index action to be executed as well, meaning the index.js.erb file in the groups folder.
  • because of the "only one render" rule I couldn't think of a nice way to do it and I am in need of a fast solution.

Thank you for any suggestions you might have.

A: 

Loading JS dynamically can introduce all sorts of complexity that I think is often best avoided. I think it's better to load all of your JS at once in a single file on page load - this way you can have a single minified script request which facilitates caching and performance.

Creating tabs can then trigger the appropriate code handling. You can start wrapping this into an event model with listeners (so code listens for tabs of the right type to be added), or you can simply call a function once the ajax request to load the has been successfully completed.

Toby Hede
Thanks... Well I guess putting it all together is a definitive solution. But at this point I have separate js files for each action of each controller and I was hoping I could keep things that way.
master2004
I do that too and package them using the excellent asset_packager. You can still include them individually in your template for development.
Toby Hede
+1  A: 

You can do it the same way you can have your create and edit views showing the same form with a partial.

_tab.html.erb
<div class="tab" id="<%= tab.id %>">
   <p>whatever</p>
</div>
show.html.erb
<%= render 'tab', :tab => TabObject %>
show.js.erb
$('#tabs.')....
$('something').append("<%= escape_javascript(render('tab', :tab => TabObject)");

And if you requesting a page with jQuery's script dataType, you really should have corresponding views because while rails will render html views in its place, jQuery will put them inside a <script> tag which isn't supposed to have html in it.

Samuel