Why Teams call analytics are critical to your entire business
jQuery - Boston Ruby Group (July '07)
1. jQuery
+ Ruby + Rails
Boston Ruby Group - July 2007
John Resig (ejohn.org)
Download this:
http://dev.jquery.com/~john/files/apple-demo.zip
2. What is jQuery?
• An open source JavaScript library that
simplifies the interaction between HTML
and JavaScript.
3. Why jQuery?
• Fully documented
• Great community
• Tons of plugins
• Small size (20kb)
• Everything works in IE 6+, Firefox,
Safari 2+, and Opera 9+
23. Using jQuery with Rails
• Most jQuery use is non different than
normal jQuery use
• $(“div”).remove(); // works on any site
• Considerations come in with dealing with
Ajax requests
24. Ajax and Rails
• Just another request to a controller/action
• You might want to respond like so:
respond_to do |format|
format.js { # do stuff }
end
• jQuery sends the right headers so you can
respond easily
25. Ajax with jQuery
• Typically, you’ll reply with an HTML chunk
• jQuery handles this gracefully:
$(“#stuff”).load(“controller/action”);
26. Reply with JSON
• Sometimes you’ll want to reply with a data
structure for further manipulation
• ActiveRecord objects have to_json
serialization built in:
quot;{attributes:{foo: quot;barquot;, baz: quot;batquot;}}quot;
• Or you can get specific: quot;{foo: quot;barquot;, baz: quot;batquot;}quot;
@ar_object.attributes.to_json #=>
27. Where does the JS go?
• jQuery dictates good separation of
content, style, and behavior
• Put all your code in application.js
• jQuery and Prototype can play nicely
together:
jQuery.noConflict();
jQuery(function($){ /* your code */ });
• More info in the docs
28. Where’s RJS?
• RJS says that sending back code (from the
server) is the best way to do things
• This is overkill, simplify and extract what
you’re trying to achieve
29. RJS v. jQuery-style
• With RJS: id=’myid’ onclick=”return someFunction
<a href=”#”
(‘myid’);”>text</a>
<a href=”#” id=’myid2’ onclick=”return someFunction
(‘myid2’);”>text</a>
• With jQuery:
<a href=”...” id=”myid”>text</a>
<a href=”...” id=”myid2”>text</a>
<script>$(“a”).click(someFunction);</script>
30. Helpers
• Say you have a link that makes an Ajax call
and updates some div with the response:
<a href='/foo/bar' rel='#baz' class='remote'>Update Baz</a>
• You might write a simple line of jQuery
code to handle it:
$(quot;a.remotequot;).click(function() { $(this.rel).load(this.href) })
31. Helpers (cont.)
• You could then write a Rails helper to
reuse it:
def remote_link text, url_hash, update = nil
link_to(text, url_hash, :class => quot;remotequot;, :rel => update)
end
• You could thenBazquot;, {:controller => quot;fooquot;,
call it as:
remote_link quot;Update
:action => quot;barquot;}, quot;#bazquot;