jQuery and Rails: Best Friends Forever

30
jQuery & Rails Best Friends Forever* *Forever as used by a 6th-grader Best Friends Forever* *Forever in the sense of a sixth grader.

description

Covers techniques on building a rich web application with jQuery and Rails. Topics include jQuery, Ruby on Rails, AJAX, JSON, and the data tag.

Transcript of jQuery and Rails: Best Friends Forever

Page 1: 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.

Page 2: jQuery and Rails: Best Friends Forever

● 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:

Page 3: jQuery and Rails: Best Friends Forever

● 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/

Page 4: jQuery and Rails: Best Friends Forever

http://www.webappers.com/infographics/javascript-frameworks-jquery.html

Popularity

Page 5: jQuery and Rails: Best Friends Forever

● 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...

Page 6: jQuery and Rails: Best Friends Forever

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/

Page 7: jQuery and Rails: Best Friends Forever

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

Page 8: jQuery and Rails: Best Friends Forever

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])

Page 9: jQuery and Rails: Best Friends Forever

Pong

http://www.bafta.org/awards/video-games/play-pong-online,678,BA.html

Page 10: jQuery and Rails: Best Friends Forever

User: Initiates Action//jQuery wrapper method$.fn.comment_photo = function() { //do stuff}

$(function() { $('.comment-photo').click(function() { $(this).comment_photo(); });})

Page 11: jQuery and Rails: Best Friends Forever

jQuery: AJAX call$.fn.comment_photo = function() { $.ajax({ url: “/comment/new", data: { photo_id: this.attr('id') }, cache: false, dataType: “html” … });}

Page 12: jQuery and Rails: Best Friends Forever

Rails: calls Controllerclass CommentsController < ApplicationController def new @comment = Comment.new respond_to do |format| format.html #new.html.erb end endend

Page 13: jQuery and Rails: Best Friends Forever

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/

Page 14: jQuery and Rails: Best Friends Forever

jQuery: displays HTML

$.fn.comment_photo = function() { $.ajax({ … success: function(html) { $('#new_comment').html(html); } });}

Page 15: jQuery and Rails: Best Friends Forever

User: more action//extending jQuery object$.extend({ create_comment: function(form) { //do stuff }});

$(function() { $('#new_comment').submit(function() { $.create_comment($(this)); });})

Page 16: jQuery and Rails: Best Friends Forever

jQuery: AJAX call create_comment: function(form) { $.ajax({ url: form.attr('action'), type: “POST”, data: { comment: form.serialize() }, cache: false, dataType: “JSON” … }); }

Page 17: jQuery and Rails: Best Friends Forever

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

Page 18: jQuery and Rails: Best Friends Forever

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 } }); }

Page 19: jQuery and Rails: Best Friends Forever

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.

Page 20: jQuery and Rails: Best Friends Forever

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}

Page 21: jQuery and Rails: Best Friends Forever

.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

Page 22: jQuery and Rails: Best Friends Forever

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

Page 23: jQuery and Rails: Best Friends Forever

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');

Page 24: jQuery and Rails: Best Friends Forever

The FutureUser jQuery Controller HTML

jQuery

User

jQueryControllerJSONjQuery

What if you want to skip thefirst AJAX call for performance?

Page 25: jQuery and Rails: Best Friends Forever

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

Page 26: jQuery and Rails: Best Friends Forever

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);

{}

Page 27: jQuery and Rails: Best Friends Forever

● Other modern javascript frameworks have much of the same functionality here, specifically YUI. You have a choice.

Disclaimer

http://developer.yahoo.com/yui/

Page 28: jQuery and Rails: Best Friends Forever

● 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/

Page 29: jQuery and Rails: Best Friends Forever

Photo Credits

● http://www.etsy.com/listing/62497842/eloise-and-ramona-play-telephone-best

● me: http://www.flickr.com/photos/just_steph/

Page 30: jQuery and Rails: Best Friends Forever

Questions?