开发者

Rails 3 js blocks: render a partial with a jquery snippet or render snippet as text?

开发者 https://www.devze.com 2023-03-07 04:24 出处:网络
I\'m working on my first \'real\' (as opposed to playing around) rails 3 project after using rails 1&2 for the last f开发者_如何学Cour years.In the destroy action\'s js block i want to do somethin

I'm working on my first 'real' (as opposed to playing around) rails 3 project after using rails 1&2 for the last f开发者_如何学Cour years. In the destroy action's js block i want to do something typical: remove the div containing the deleted resource on the page.

I can't decide whether it's better to render out a destroy.js.erb file like so: (the resource in question is a 'note' and the method .dom_id just returns a string like "note_#{note.id}".)

Approach A: render a js view file

#in controller
  format.js

#in views/notes/destroy.js.erb
$('#<%= @note.dom_id %>').remove();

This has the advantage of keeping the controller totally clean and standard.

Approach B: put the js in the controller:

#in controller
format.js { render :text => "$('##{@note.dom_id}').remove()" }

This has the advantage of enabling the person looking at the controller code to instantly see what's going on, without going hunting for a view file with one line of code in it. On the other hand, it breaks MVC.

What do you think? Which is more 'proper', 'standard', etc? Is there a third (fourth, fifth) way that's even better?


I would tend to follow Approach A, even though you may only have a few lines worth of code. The reason is that you may have a teammate that sees Approach B and decides that when you need to add more JavaScript to the render, doing it inline is the correct approach. Inlining JavaScript can (according to what I've read) be used for very simple one one-liners, but even then it's not recommended.

If you want to avoid having to look around for the proper JS view file, you can always render a specific file rather than following the "file --> controller action" naming convention. That way the exact js.erb file you're using is clear in your controller.

0

精彩评论

暂无评论...
验证码 换一张
取 消