views:

854

answers:

2

I'm starting to look into the whole world of RJS and Prototype/jQuery in rails and am a little bit confused. There seems to be no clear line of where to use one or the other.

Say i wanted one of the "Active, Hot, Week" tabs like the ones here on SO. When pressing one of them i want to remove a css class (like "active-tab") from the one i was on and add it to the one i clicked on. Then i also want to reload the div containing the items and put in the new items into it.

Seems the class-changing thing would be easiest to do in pure javascript, say put the code in application.js and then updating the div with the content would obviously be easiest in RJS. But what should one do?

+1  A: 

If you want to give users that ability to link to the generated page directly, then definitly go for a static page. Using AJAX breaks the back button unless you use something like Really Simple History (which is not 100% cross browser), so going the JS route with your page navigation will almost certainly cause some of your users problems.

That said, what you have discussed already would be fine, I think - just have a class change in your RJS file, then you might even find it useful to update the div contents using page.replace and a partial:

page.replace(dom_id, :partial => @page_content);
Mr. Matt
+2  A: 

If you're comfortable with writing JavaScript then by all means use JavaScript. There's nothing wrong with that; you don't have to use RJS just because it exists. In fact you'll probably find that its abstractions get in the way.

However, if you'd rather write Ruby code that generates JavaScript, just as you write Ruby code that generates SQL in ActiveRecord Migrations, then RJS is the right tool for the job. Or you can use both: RJS for fairly simple things and then drop down to JavaScript for more complex behaviour. Use what feels right to you.

John Topley