It's just not clear to me how to use Rails JS templates well. They're essentially replacing the success callback on an AJAX request, right? Why would it ever make sense to separate the JS executed when the request is a success from the JS that executes for the various other callb开发者_运维技巧acks?
This of course assumes that I'm binding a click handler or something to a link and making an AJAX request that way. I could of course be using a link_to
with :remote => true
. I suppose in that case it might make sense to use JS templates. But then what do you do if you need to handle other cases besides success? Bind an ajax:failure
event to the link generated by the link_to
? That would mean maintaining JS related to that link in two separate places. And what happens if there's two links (say, with different markup) that both make a request to that action, but each one requiring different JS to be executed because they need to behave differently when clicked? How would you handle that with a JS template?
Am I thinking about this right?
I think the best way is to avoid the js templates. It's an aberration to try to write js code in ruby... It's my opinion, but the alternative is much cleaner and simpler because you write the code in the actual language. So, write your javascript that makes the call to the url provided in your link, and then ask for the content in json. In your controller, just return the data in json (it can be a list of object with data, or just an object like: {success: true} or {success: false}. Then in your js you treat the object and make the appropiate action. In different parts that point to the same url you can take different actions in your js.
You would use embedded Ruby (as your javascript templates are js.erb files).
If you wanted different sets of javascript to be executed depending on success or failure you'd do something like:
Controller:
def my_action
#some code
@success = true #or false
respond_to do |format|
format.js #you may need to add render :layout => false
format.html #html fallback
end
end
Then in my_action.js.erb view:
<% if @success %>
//Some javascript for success
<% else %>
//Some javascript for failure
<% end %>
精彩评论