RailsCasts - Ruby on Rails Screencasts

RailsCasts Pro episodes are now free!

Learn more or hide this

Unobtrusive Javascript

#205 Unobtrusive Javascript

Mar 15, 2010 | 13 minutes | Views, Ajax, Rails 3.0
Keep JavaScript out of your HTML content with unobtrusive JavaScript. Here I show how Rails 3 works with this best practice.
Click to Play Video ▶
Tweet
  • Download:
  • source code Project Files in Zip (163 KB)
  • mp4 Full Size H.264 Video (18.8 MB)
  • m4v Smaller H.264 Video (13.4 MB)
  • webm Full Size VP8 Video (35 MB)
  • ogv Full Size Theora Video (25.6 MB)
Browse_code Browse Source Code

Resources

ujs_example.html
<!DOCTYPE html>
<html>
 <head>
 <title>UJS Example</title>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
 <script type="text/javascript" charset="utf-8">
 $(function() {
 $("#alert").click(function() {
 alert(this.getAttribute("data-message"));
 return false;
 })
 })
 </script>
 </head>
 <body>
 <h1><a href="#" id="alert" data-message="Hello UJS!">Click Here</a></h1>
 </body>
</html>
layouts/application.html.erb
<%= javascript_include_tag :defaults %>
<!-- or -->
<%= javascript_include_tag "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js", "jquery.rails.js" %>
<%= csrf_meta_tag %>
products/index.html.erb
<% form_tag products_path, :method => :get, :remote => true do %>
 <p>
 <%= text_field_tag :search, params[:search] %>
 <%= submit_tag "Search", :name => nil %>
 </p>
<% end %>
<div id="products">
 <%= render @products %>
</div>
products/index.js.erb
$("products").update("<%= escape_javascript(render(@products)) %>");
// or
$("#products").html("<%= escape_javascript(render(@products)) %>");
loading

AltStyle によって変換されたページ (->オリジナル) /