jQuery and Rails: Best Friends Forever
-
Upload
stephskardal -
Category
Technology
-
view
31.587 -
download
2
description
Transcript of jQuery and Rails: Best Friends Forever
jQuery & RailsBest Friends Forever*
*Forever as used by a 6th-grader
Best Friends Forever*
*Forever in the sense of a sixth grader.
● Brief Rails explanation
● Brief jQuery explanation
● Nice methods between each technology to encourage a rich web app
● AJAX● JSON● data
● The Future
I'll Cover:
● is a JavaScript framework (YUI, prototype, scriptaculous)
● includes basic JavaScript functionality for AJAX, DOM manipulation, events
● likes to hang out with jQuery UI, user interface library, interactions, widgets, effects, themes
● is known for being concise and readable
jQuery...
http://jqueryui.com/
http://www.webappers.com/infographics/javascript-frameworks-jquery.html
Popularity
● is a MVC framework built on Ruby
● is a tool for efficient development that follows universal conventions
● is designed to work well with JavaScript + AJAX
Ruby on Rails...
AJAX in jQuery$.ajax({ url: "test.html", data: $('#form').serialize(), type: “POST”, cache: false, dataType: “html”, success: function(){ //do something }, error: function() { //do something else }});
http://api.jquery.com/jQuery.ajax/
Rails Tidbits●Routing: connects URLs to Code match “/products/:id” => “products#show”
●Handling different responses respond_to do |format| format.html format.xml { … } end
●Handling JSON response respond_to do |format| format.json { render :json => data } end
Rails Tidbits●Request object request.xhr?
●Handling CGI parameters params[:name], params[:description] params.has_key?(:name)
p = Product.new(params[:product]) p.save # check for p.errors
product.update_attributes(params[:product])
Pong
http://www.bafta.org/awards/video-games/play-pong-online,678,BA.html
●
User: Initiates Action//jQuery wrapper method$.fn.comment_photo = function() { //do stuff}
$(function() { $('.comment-photo').click(function() { $(this).comment_photo(); });})
jQuery: AJAX call$.fn.comment_photo = function() { $.ajax({ url: “/comment/new", data: { photo_id: this.attr('id') }, cache: false, dataType: “html” … });}
Rails: calls Controllerclass CommentsController < ApplicationController def new @comment = Comment.new respond_to do |format| format.html #new.html.erb end endend
Rails: renders HTML<% form_for @comment do |f| %> <%= f.label :title %> <%= f.text_field :title %>
<%= f.label :data %> <%= f.text_area :data %>
<%= f.submit %><% end %>
<form action= “/comments” method=”post”><label for=“comment_title”>Title</label><input type=“text” id=“comment_title” name=“comment[title]” />
<label for=“comment_data”>Data</label><textarea id=“comment_data” name=“comment[data]” /></textarea>
<input type=“submit” id=“comment_submit” value=”Create ” /></form>
erb HTML
http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/
●
jQuery: displays HTML
$.fn.comment_photo = function() { $.ajax({ … success: function(html) { $('#new_comment').html(html); } });}
User: more action//extending jQuery object$.extend({ create_comment: function(form) { //do stuff }});
$(function() { $('#new_comment').submit(function() { $.create_comment($(this)); });})
jQuery: AJAX call create_comment: function(form) { $.ajax({ url: form.attr('action'), type: “POST”, data: { comment: form.serialize() }, cache: false, dataType: “JSON” … }); }
Rails: calls Controllerclass CommentsController < ApplicationController def create begin comment = Comment.new(params[:comment]) comment.user = current_user comment.save respond_to do |format| format.json :json => comment end rescue Exception => e render :status => 500, :json => {} end endend
jQuery: success! create_comment: function(comment) { $.ajax({ … success: function(result) { $('#new_comment').hide(); //feedback to communicate success }, error: function(xhr, status, error) { //feedback to communicate error } }); }
Perl Module can use JSON module to setScratch variable to JSON-ified data.
Perl Module will set mv_nextpage and set Scratch variables.
InterchangeUser jQuery ActionMap Perl Module
HTML
jQuery
UserjQueryActionMapPerl Module
JSON
jQuery
ActionMap will route URL to desiredfunctionality.
Paginationrespond_to do |format| format.html do if request.xhr? render :partial => 'item_block' else render 'index' end endend
dataType: “html”
success:function() { //replace HTML //apply listeners //replace pagination}
.js & js.erbIt's worth noting that you can also return JavaScript or JavaScript from a js.erb file as a Rails controller response. erb is a templating language. The resulting JavaScript will be executed by jQuery.
I prefer returning JSON, because I've seen this be finicky and it can be difficult to debug.
respond_to do |format| format.js { render :text => "alert('hello')" } end
JSONjQuery and JavaScript Rails
var obj = $.parseJSON(string);//parse a string into a JSON object
JSON.stringify(obj);//stringify a JSON object into JSON//text for use as argument string
render :json => comment # automatically calls to_json
to_json# converts objects to string# arguments: only, except, include# nested resources
http://api.rubyonrails.org/classes/ActiveRecord/Serialization.html
data tag & HTML5
everything in moderation.
<div id=“comment” data-id=“<%= comment.id %>”></div>
Rails
jQuery$('.comment').data('id');$('.comment').data('id', 123);$('.comment').removeData('id');
The FutureUser jQuery Controller HTML
jQuery
User
jQueryControllerJSONjQuery
What if you want to skip thefirst AJAX call for performance?
The FutureOptions for eliminating first AJAX call
● Render HTML form inline (once)
● Render HTML form in JavaScript with jQuery HTML builder nodes
● Use a template system like Mustache.js or Handlebars.js
● Use a JavaScript [client-side] Model-View framework like Backbone.js
Mustache.js
var comment_template = “<h3>{{header}}</h3>\<p class=“error”></p>\<label for=“title”>Title</label>\<input type=“text” name=“title” value=“{{title}}” />\<label for=“data”>Data</label>\<textarea name=“data”>{{data}}</textarea>\<input type=“submit” value= “submit” />”;
http://mustache.github.com/
New
Edit
var comment = { header: “Comment on This!”};$.mustache(comment_template, comment);
var comment = { header: “Edit your Comment!”, title: “Awesome”, data: “This is an awesome photo.”};$.mustache(comment_template, comment);
{}
● Other modern javascript frameworks have much of the same functionality here, specifically YUI. You have a choice.
Disclaimer
http://developer.yahoo.com/yui/
● jQuery and Rails work together to write rich web applications.
● jQuery is most popular and known for it's conciseness and readability, and unique “chaining” method
● DIG into the documentation. jQuery and Ruby documentation is good. Rails is “up and coming”.
jQuery & Rails
http://visualjquery.com/
Photo Credits
● http://www.etsy.com/listing/62497842/eloise-and-ramona-play-telephone-best
● me: http://www.flickr.com/photos/just_steph/
Questions?