A simple Rails AJAX question
Sorry for the newb question, oh wise ones.
I want to bind a checkbox click in a "p开发者_JAVA技巧rojects" view to a js function that massages the data and then sends it via ajax to the "complete" action of a "tasks" controller.
I'm using jQuery, so instinctively I put the binding and callbacks all in application.js, but this is obviously not right. What is the best and most unobtrusive way to do this?
Thanks!
If you have a function that only belongs in, say, the index view of projects controller, then you might do the following.
Add a yield :head
in the section of your layout. This will allow you to add content to the header later, next--
In the view (i.e. views/projects/index.html.erb', add:
<% content_for :head do %>
javascript_include_tag 'projects_index.js'
<% end %>
In javascripts/projects_index.js, use a document ready block and bind the event handler.
Notes
- I'm not sure if "unobtrusive" is what you're asking for.
- Sending ajax requests when a checkbox is clicked might doesn't seem very consistent with expectations
Unobtrusive is a poorly defined term, but I take it to mean a few things including progressive enhancement (letting the small fraction of the Internet not running JavaScript still use your application) and separation of content from functionality (same thing as styles not being applied directly to DOM elements). This means that if you want to be truly "unobtrusive" you should be doing something similar to what you say.
However, in Rails you will typically handle the callbacks using a new 'view'. Check out the RJS template language that lets you easily render JavaScript to be executed on the client. Here is a quick example:
# application.js
$("#project .complete:checkbox").click(function () {
$.post('/projects/complete', {...});
})
# projects_controller.rb
def complete
@project = Project.find(...)
respond_to do |format|
format.js
end
end
# complete.js.rjs
page << "$('##{dom_id(@project)}').effect('highlight');"
Note: you can use most template language (such as ERB), However I usually use RJS for doing things like this.
精彩评论