Upload
shen-liu
View
4.166
Download
6
Tags:
Embed Size (px)
DESCRIPTION
By Zhao Lu
Citation preview
jQuery in RailsLouie Zhao
Co - Founder
Caibangzi.com & IN-SRC Studio
1
Problem
• JavaScript programming can be hard
• Completely dynamic language
• JavaScript, by itself, isn’t useful
2
3
var tables = document.getElementsByTagName('table');for (var t = 0; t < tables.length; t++) { var rows = tables[t].getElementsByTagName('tr'); for(var i = 1; i < rows.length; i += 2) { if (!/(^¦s)odd(s¦$)/.test(rows[i].className)) { rows[i].className += ' odd'; } }}
jQuery('table tr:nth-child(odd)').addClass('odd');
JavaScript Library
• Drastically simplify DOM, Ajax, Animation
4
5
jQuery
• An open source JavaScript library that simplifies the interaction between HTML and JavaScript.
6
7
time.comtwitter.com
wordpress.comamazon.com ibm.com
microsoft.com
8
jQuery
• Cross Browser
• Small
• Lean API, fun coding
9
jQuery Overview
• Selector & Chaining
• DOM manipulation
• Events
• Effects
• Ajax
10
Selector & Chaining
11
$(selector).method1().method2().method3();
$('#goAway').hide().addClass('incognito');
Selector
12
• Basic CSS selectors
• Positional selectors
• Custom jQuery selectors
Basic CSS Selector
13
$('li>p')
Basic CSS Selector
14
$('div.someClass')
Basic CSS Selector
15
$('#testButton')
Basic CSS Selector
16
$('img[alt]')
Basic CSS Selector
17
$('a[href$=.pdf]')
Basic CSS Selector
18
$('button[id*=test]')
Positional Selectors
19
$('p:first')
Positional Selectors
20
$('img[src$=.png]:first')
Positional Selectors
21
$('button.small:last')
Positional Selectors
22
$('li:first-child')
Positional Selectors
23
$('a:only-child')
Positional Selectors
24
$('li:nth-child(2)')$('li:nth-child(odd)')$('li:nth-child(5n)')$('li:nth-child(5n+1)')
Positional Selectors
25
$('.someClass:eq(1)')$('.someClass:gt(1)')$('.someClass:lt(4)')
Custom Selectors
26
$(':button:hidden')$('input[name=myRadioGroup]:radio:checked')$(':text:disabled')$('#xyz p :header')$('option:not(:selected)')$('#myForm button:not(.someClass)')$('select[name=choices] :selected')$('p:contains(coffee)')
Add / Remove
27
$('div').css('font-weight','bold').add('p').css('color','red');
$('body *').css('font-weight','bold').not('p').css('color','red');
Find / Slicing
28
$('div').css('background-color','blue').find('img').css('border','1px solid aqua');
$('body *').slice(2,3).hide();
Matching by Relationship
29
.parents("tr:first")
Map
30
var values = $('#myForm :input').map(function(){ return $(this).val();});
Controlling Chaining
31
$('div').add('p').css('color','red').end().hide();
$('div').css('background-color','yellow').children('img').css('border','4px ridge maroon').andSelf().css('margin','4em');
DOM Manipulation
• Changing contents
32
.html("<p>This is a paragraph.</p>")
.text("<p>This is a paragraph.</p>")
DOM Manipulation
• Inserting inside
• append(content)
• appendTo(selector)
• prepend(content)
• prependTo(selector)
33
DOM Manipulation
• Inserting outside
• after(content)
• insertAfter(selector)
• before(content)
• insertBefore(selector)
34
DOM Manipulation
• Inserting around
• Replacing
• Removing
• Copying
35
Events
• Page Load
• Event Handling
• Live Events
• Event Helpers
36
Events
• Run after DOM, but before images
37
$(document).ready(function() {});
Effects
38
Ajax
• Cross browser
39
$.ajax();
$.load();
$.get();
$.post();
jQuery UI
• Interactions
• Widgets
40
Interactions
• Draggable
• Droppable
• Resizable
• Selectable
• Sortable
41
Widgets
• Accordion
• Date picker
• Dialog
• Progress Bar
• Slider
• Tabs
42
Prototype - Controller
43
class BooksController < ApplicationController def create @book = Book.create!(params[:book]) respond_to do |format| format.html { redirect_to books_path } format.js end endend
Prototype - View
44
<!-- layouts/application.rhtml --><%= javascript_include_tag :defaults %>
<!-- layouts/show.rhtml --><% form_remote_for :book, :url => books_path %> ....<% end %>
<!-- app/views/books/create.js.rjs -->page.insert_html :bottom, :books, :partial => 'book'
jQuery - View
45
<!-- app/views/books/create.js.erb -->$("#books").append("<%= escape_javascript(render(:partial => @book)) %>");
<!-- public/javascripts/applicaton.js -->$(document).ready(function() { $("#new_book").submit(function() { $.post($(this).attr("action"), $(this).serialize(), null, "script") return false; }); });
<!-- layouts/application.rhtml --><%= javascript_include_tag 'jquery', 'jquery-ui', 'application' %>
jQuery - View
46
jQuery.fn.submitWithAjax = function() { this.submit(function() { $.post($(this).attr("action"), $(this).serialize(), null, "script") return false; }); };
$(document).ready(function() { $("#new_book").submitWithAjax();});
delete
47
class BooksController < ApplicationController def destroy @book = Book.find params[:id] @book.destroy redirect_to books_path endend
<tr id="book_<%= book.id %>"> <td><%= h book.title %></td> <td><%= h book.author %></td> <td><%= book.price %></td> <td><%= book.published_on.to_s %></td> <td><%= link_to 'X', book_path(book), :method => :delete %></td></tr> <a onclick="var f = document.createElement('form');
f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method'); m.setAttribute('value', 'delete'); f.appendChild(m);var s = document.createElement('input'); s.setAttribute('type', 'hidden'); s.setAttribute('name', 'authenticity_token'); s.setAttribute('value', 'tOF2pTCCgIb1VcazauJe+JylUT1jpWSK8SLsBu2YDiw='); f.appendChild(s);f.submit();return false;" href="/books/23">X</a>
delete
48
<td> <%= link_to 'X', book_path(book), :class => "delete" %></td>
$(document).ready(function() { $("a.delete").click(function(){ $.ajax({ type: "DELETE", url: this.href }); $(this).parents("tr:first").remove(); return false; });});
Date Picker
49
$("#book_published_on").datepicker();
Ajax Pagination
50
<h2>Book List</h2><%= will_paginate @books %><table> <tbody id="books"> <%= render :partial => 'book', :collection => @books %> </tbody> </table><%= will_paginate @books %>
class BooksController < ApplicationController def index @books = Book.all.paginate :per_page => 1, :page => params[:page] endend
Ajax Pagination
51
<h2>Book List</h2><div id="paginated_books"><%= render :partial => 'books' %></div>
<%= will_paginate @books %><table> <tbody id="books"> <%= render :partial => 'book', :collection => @books %> </tbody> </table><%= will_paginate @books %>
Ajax Pagination
52
$(document).ready(function() { $(".pagination a").live("click", function() { $(".pagination").html("loading...."); $.get(this.href, null, null, "script"); return false; });});
$("#paginated_books").html("<%= escape_javascript(render('books')) %>")
index.js.erb
application.js
.click(function() ....live(“click”, function() ...
Thanks!
53