Jquery Air 2 Slides
-
Upload
m-y-hassan -
Category
Documents
-
view
45 -
download
0
description
Transcript of Jquery Air 2 Slides
EVENTS
04 Using Bind for Events
03 Data Tags
02 Namespacing the $
01 Reading from the DOM (Review)
TABLE OF CONTENTS
05 Unbinding Events
06 Live & Delegate
EVENTS
$('#tabs ul li:first').html();
<a href="#2012-09-27" data-flights="6">Sep 27</a>
$('#tabs ul li:first a').text(); Sep 27
$('#tabs ul li:first a').attr('href'); #2012-09-27
$('#tabs ul li:first a').data('flights'); 6
<section id="tabs"> <ul> <li><a href="#2012-09-27" data-flights="6">Sep 27</a></li> <li><a href="#2012-09-28" data-flights="5">Sep 28</a></li> <li><a href="#2012-09-29" data-flights="5">Sep 29</a></li> </ul></section>
Reading from the DOM HTML 5 data attribute
EVENTS
<section id="tabs"> <ul> <li><a href="#2012-09-27" data-flights="6">Sep 27</a></li> <li><a href="#2012-09-28" data-flights="5">Sep 28</a></li> <li><a href="#2012-09-29" data-flights="5">Sep 29</a></li> <li><a href="#2012-09-30" data-flights="3">Sep 30</a></li> <li><a href="#2012-10-01" data-flights="3">Oct 1</a></li> </ul></section>
$("#tabs li a").click$(document).ready(function(){
(function(e){
});});
e.preventDefault();$("#tabs li a.active").removeClass("active");$(this).addClass("active");
Making the Tabs Work
EVENTS
and ensures $ refers to jQueryExecutes once DOM is loaded
function changeTab(e) {
}
e.preventDefault();$("#tabs li a.active").removeClass("active");
$("#tabs li a").click
jQuery(function($) {
(changeTab);});
Cleaning up the Code
$(this).addClass("active");
EVENTS
What we have so far
function changeTab(e) {
}
e.preventDefault();$("#tabs li a.active").removeClass("active");$(this).addClass("active");
EVENTS
Selects the 3rd element
$("#tabs li a").click(changeTab);$("#tabs li:eq(2) a").click();
Select the Default Viewfunction changeTab(e) {
}
e.preventDefault();$("#tabs li a.active").removeClass("active");$(this).addClass("active");
EVENTS
<section id="tabs"> <ul> <li><a href="#2012-09-27" data-flights="6">Sep 27</a></li> <li><a href="#2012-09-28" data-flights="5">Sep 28</a></li> <li><a href="#2012-09-29" data-flights="5">Sep 29</a></li> <li><a href="#2012-09-30" data-flights="3">Sep 30</a></li> <li><a href="#2012-10-01" data-flights="3">Oct 1</a></li> </ul></section>
What we have so far
Create a tool tip with the data tag
EVENTS
function showNumberOfFlights(e) {
$(this).append("<span class='tooltip'>" + num_flights+ " flights</span>");
function hideNumberOfFlights(e) { $("#tabs span.tooltip").remove();}
var num_flights = $(this).data('flights');
}
$("#tabs li a").click(changeTab);););
((showNumberOfFlightshideNumberOfFlights
mouseenter$("#tabs li a").$("#tabs li a").mouseleave
Create Tooltip with Data Tag
EVENTS
$("#tabs li a").click changeTab
showNumberOfFlightshideNumberOfFlights
mouseenter
$("#tabs li a").$("#tabs li a").
mouseleave});
.bind({:
::
,
Using Bind for Multiple Eventsfunction showNumberOfFlights(e) {
$(this).append("<span class='tooltip'>" + num_flights+ " flights</span>");
function hideNumberOfFlights(e) { $("#tabs span.tooltip").remove();}
var num_flights = $(this).data("flights");
}
,
EVENTS
click changeTabshowNumberOfFlightshideNumberOfFlights
mouseentermouseleave
});
.bind({:
::
,,
What we have so far
$("#tabs li a").$("#tabs li a").$("#tabs li a").
EVENTS
04 Using Bind for Events
03 Data Tags
02 Namespacing the $
01 Reading from the DOM (Review)
TABLE OF CONTENTS
05 Unbinding Events
06 Live & Delegate
EVENTS
</section>
<section id="tabs"> <ul>
<li><a href="#2012-09-27" data-flights="6">Sep 27</a></li><li><a href="#2012-09-28" data-flights="5">Sep 28</a></li><li><a href="#2012-09-29" data-flights="5">Sep 29</a></li><li><a href="#2012-09-30" data-flights="3">Sep 30</a></li><li><a href="#2012-10-31" data-flights="3">Oct 1</a></li>
</ul>
<div id="2012-09-27">Loading Sep 27</div><div id="2012-09-28">Loading Sep 28</div><div id="2012-09-29">Loading Sep 29</div><div id="2012-09-30">Loading Sep 30</div><div id="2012-10-01">Loading Oct 1</div>
Lets Add Divs!
EVENTS
$("#tabs div").hide();
$(activeDiv).show();}
$(this).attr("href");var activeDiv =
Switching Between Divs
</section>
<section id="tabs"> <ul>
<li><a href="#2012-09-27" data-flights="6">Sep 27</a></li>
<div id="2012-09-27">Loading Sep 27</div>
</ul>
function changeTab(e) { e.preventDefault(); $("#tabs li a.active").removeClass("active"); $(this).addClass("active");
EVENTS
$("#tabs div").hide();$(activeDiv).show();
}
}
function showFlights(activeDiv) {
showFlights( ;)
Refactor
</section>
<section id="tabs"> <ul>
<li><a href="#2012-09-27" data-flights="6">Sep 27</a></li>
<div id="2012-09-27">Loading Sep 27</div>
</ul>
$(this).attr("href")
function changeTab(e) { e.preventDefault(); $("#tabs li a.active").removeClass("active"); $(this).addClass("active");
EVENTS
What we have so far
$("#tabs div").hide();$(activeDiv).show();
}
}
function showFlights(activeDiv) {
showFlights( ;)$(this).attr("href")
function changeTab(e) { e.preventDefault(); $("#tabs li a.active").removeClass("active"); $(this).addClass("active");
EVENTS
(We’ll learn about AJAX later)
fetchFlights(activeDiv);
Loads the proper flight data
Load Flights with AJAX
$("#tabs div").hide();$(activeDiv).show();
}
}
function showFlights(activeDiv) {
showFlights( ;)$(this).attr("href")
function changeTab(e) { e.preventDefault(); $("#tabs li a.active").removeClass("active"); $(this).addClass("active");
EVENTS
.bind("click", changeTab);
same asfunction changeTab(e) { e.preventDefault(); $("#tabs li a.active").removeClass("active") $(this).addClass("active") ...
.click(changeTab);.unbind("click", changeTab);
Unbind the Event
EVENTS
.bind("click.flightSchedule", changeTab);
.unbind("click.flightSchedule")
$("#tabs li a").bind({ "click.flightSchedule": changeTab, "mouseenter.flightSchedule": showNumberOfFlights, "mouseout.flightSchedule": hideNumberOfFlights});
$("#tabs li a").unbind(".flightSchedule")
Now you can unbind everything
Or alternatively
Namespacing Your Events
EVENTS
<table id="flights"> ... <tr> <td>3:15 PM</td> <td>5:08 PM</td> <td>1946</td> <td>2 stops</td> <td><a href="#" class="selected">$276</a></td> <td><a href="#">$205</a></td> </tr> ...</table>
Allowing Users to Select a Flight
EVENTS
It doesn’t work!
function selectFlight(e) {e.preventDefault();$("#flights a.selected").removeClass("selected");$(this).addClass("selected");
}
$("#flights a").bind("click", selectFlight);
Selecting a Flight
EVENTS
Live - For Binding Selectors Now and in the Future function selectFlight(e) {e.preventDefault();$("#flights a.selected").removeClass("selected");
}
$("#flights a").live("click", selectFlight);
$(this).addClass("selected");
EVENTS
$("#flights a").live("click", selectFlight);
same as
$("#tabs div").delegate("#flights a", "click", selectFlight);
Delegate has Benefitscan be method chainedmore performant
Delegate vs Live
Check inside this element, rather than entire page
$(document).delegate("#flights a", "click", selectFlight);
AJAX
04 Receiving and Parsing JSON
03 Aborting AJAX & Timeouts
02 AJAX Error Handling & Callbacks
01 Basic AJAX
TABLE OF CONTENTS
05 Using JSONP
06 Sending Form Data
★ Code from Level 1
AJAX
Basic AJAX
$("#tabs div").hide();$(activeDiv).show();
}
function showFlights(activeDiv) {
fetchFlights(activeDiv);
We need to write the AJAX
AJAX
Basic AJAX $("#tabs div").hide();$(activeDiv).show();
}
function showFlights(activeDiv) {
$.ajax('/flights', {data: { date: activeDiv },success: function(result) {
} }});
$(activeDiv).html(result);
/flights?date=%232012-09-30(#)
We’re showing the DIV before it’s loaded
AJAX
$.get Alternate Syntax
$(activeDiv).show();
$.ajax('/flights', {data: { date: activeDiv },success: function(result) {
} }});
$(activeDiv).html(result);
$.get("/flights", { date: activeDiv }, function(result) { $(activeDiv).html(result); $(activeDiv).show(); });
AJAX
AJAX cache option
$(activeDiv).show();
$.ajax('/flights', {data: { date: activeDiv },
success: function(result) {
} }});
$(activeDiv).html(result);
cache: false,
Reloads all data
AJAX
Add Error Handling
$(activeDiv).show();
$.ajax('/flights', {data: { date: activeDiv },
success: function(result) {
}});
$(activeDiv).html(result);
cache: false,
},error: function(result) {$('#error').show();
}
$('#error').hide();beforeSend: function(result) {
},
AJAX
Add Error Handling
<div id="error"> <h2>Whoops, unable to pull flights.</h2> <p>Sorry about that, <a href='#'>Click Here</a> to try again.<p></div>
$("#error a").click(function (e){ e.preventDefault(); showFlights($("#tabs li a.active").attr("href"));});
<div id="2012-10-01"></div>
In HTML
In JavaScript
AJAX
Add Loading Screen
<div id="error"> <h2>Whoops, unable to pull flights.</h2> <p>Sorry about that, <a href='#'>Click here</a> to try again.<p></div>
<div id="2012-10-01"></div>
In HTML
<div id="loading"> <h2>Just a minute while we pull up your flight</h2> </div>
AJAX
More Callbacks $.ajax('/flights', { data: { date: activeDiv }, cache: false,
beforeSend:
complete:
success: ...error: ...
});
function() {
function() {
$('#loading').show();},
$('#loading').hide();},
Before AJAX invoked
When AJAX returns
If returns successfullyIf doesn’t return successfully
$('#error').hide();
AJAX
Need to abort incomplete AJAX requests
$.ajax('/flights', {
});...
function showFlights(activeDiv) { $("#tabs div").hide();
}
Getting called every time a tab is clicked
AJAX
Need to abort incomplete AJAX requests
$.ajax('/flights', {
});
...
function showFlights(activeDiv) { $("#tabs div").hide();
}
var fetchingFlights = null;
if (fetchingFlights) {
}fetchingFlights.abort();
fetchingFlights =
complete: function(result) { $('#tabs #loading').hide(); fetchingFlights = null;}
AJAX
Abort triggers the error callback
$.ajax('/flights', {
});
...
function showFlights(activeDiv) { $("#tabs div").hide();
}
if (fetchingFlights) {
}fetchingFlights.abort();
fetchingFlights =
complete: function(result) { $('#tabs #loading').hide(); fetchingFlights = null;}
if (result.statusText != "abort") {
}$('#tabs #error').show();
error: function(result) {
}Don’t show error if aborted
AJAX
Adding a timeout
});
...After 8 seconds will error out
fetchingFlights = $.ajax('/flights', { data: { date: activeDiv }, cache: false,
if (result.statusText != "abort") {
}$('#tabs #error').show();
error: function(result) {
}
timeout: 8000,
AJAX
04 Receiving and Parsing JSON
03 Aborting AJAX & Timeouts
02 AJAX Error Handling & Callbacks
01 Basic AJAX
TABLE OF CONTENTS
05 Using JSONP
06 Sending Form Data
AJAX
Fetching Data using JSON
var flight = $(this).data('flight');var flightClass = $(this).data('class');
function selectFlight(e) { e.preventDefault(); $("#tabs a.selected").removeClass('selected'); $(this).addClass('selected');
$('#confirm').hide();
data: { 'class': flightClass },dataType: 'json',
});
$.ajax('/flights/' + flight, {
showTotalsuccess: $.getJSON('/flights/' + flight,
{ 'class': flightClass }, showTotal);
Same as
AJAX
Fetching Data using JSON
data: { 'class': flightClass },dataType: 'json',
});
$.ajax('/flights/' + flight, {
showTotalsuccess:
$('#price').text(json.price);$('#fees').text(json.fees);$('#total').text(json.total);$('#confirm').slideDown();
function showTotal(json) {
}
<section id="confirm"> <div class="flight-review"> <table> <tr> <th>Base Price:</th> <td id="price"></td> </tr> <tr> <th>Govt. Taxes:</th> <td id="fees"></td> </tr> <tr class="total"> <th>Trip Total:</th> <td id="total"></td> </tr> </table> </div>
AJAX
Fetching Data Using JSONP
How you fetch JSON data from a different domain
$.ajax('http://other.com/flights/' + flight, { data: { 'class': class }, dataType: 'jsonp', success: showTotal});
function fetchWeather() { $.ajax('http://api.wunderground.com/api/./conditions/q/32789.json', { dataType: 'jsonp', success: function(json) { alert(json.current_observation.temperature_string); } });}
Your API key
AJAX
The Login Form <div id="login"> <form> <h4>Please login to book flight:</h4> <p> <label>Email:</label> <input type='email' name='email' id='email' /> </p> <p> <label>Password:</label> <input type='password' name='password' id='password' /> </p> <p> <input type='submit' value="Login" /> </p> </form> </div>
AJAX
Pulling Email and Password $('#login form').submit(login);
function login(e) { e.preventDefault(); $('#login h4').slideUp();
var email = $('#login #email').val();var password = $('#login #password').val();
$.ajax('/login', { data: { 'email':email, 'password':password }, ...
AJAX
Serialize & Scriptfunction login(e) { e.preventDefault(); $('#login h4').slideUp();
var form = $(this).serialize();
$.ajax('/login', { data: form, dataType: 'script', type: 'post'});
email=<email>&password=<pass>
Expecting JavaScript to execute
}
AJAX
Server-Side Generated JavaScript/app/views/sessions/create.js.erb (Rails app)<% if @logged_in %>
<% else %>
<% end %>
$('#login').html("<%= escape_javascript(render 'welcome') %>");
$('#confirm .confirm-purchase').slideDown();
$("#confirm tr.total td").css('background-color', '#2C1F11');
$('#login h4').text("Invalid Email/Password. Try Again").slideDown();
Insert welcome message
Show purchase button
Highlight total price
Effects
04 Using a Queue
03 Effect Easing
02 Animating with CSS
01 Chaining Effects & Adjusting Speed
TABLE OF CONTENTS
05 Adding a Delay
06 Stopping an Effect
Effects
Adding Fade In & Out to Login Box
Chain effects$('#login').fadeOut().html(...).fadeIn();
$('#login').html(...);
http://api.jquery.com/category/effects/Effect docs
Effects
Adding a Callback to Effects
Use callback
$('#login').fadeOut().html(...).fadeIn();
$('#login').fadeOut(function() { $(this).html(...).fadeIn();});
$('#login').fadeOut('fast', function() { $(this).html(...).fadeIn('slow');});
Adjust speed
Effects
Effect Speed Settings
Default400 ms
200 ms
600 ms
$('#login').fadeOut(1000)
Custom Time1000 ms
'slow'
'fast'
(1 second)
Effects
Animate Total to Call Attention $("...").css('background-color', '#2C1F11');
$("...").css({'background-color': '#2C1F11'}) .animate({ height: '30'});
$("...").css({'background-color': '#2C1F11', 'opacity':'0.5'}) .animate({ opacity: '1', height: '30'}, 'slow');
FYI. Could use classes & CSS animations
Change height
Flash a little
Effects
Change Easing of Confirmation to Linear $('#confirm .confirm-purchase').slideDown(500, 'linear');
$("...").css({'background-color': '#2C1F11', 'opacity':'0.5'}) .animate({ opacity: '1', height: '30'}, 'slow', 'linear');
Effects
04 Using a Queue
03 Effect Easing
02 Animating with CSS
01 Chaining Effects & Adjusting Speed
TABLE OF CONTENTS
05 Adding a Delay
06 Stopping an Effect
Effects
Refactoring Login
$.ajax('/login', { data: form, dataType: 'script', type: 'post'});
Successful login returns
But why not fade out before the AJAX?
$('#login').fadeOut('fast', function() {$(this).html(...).fadeIn('slow');
});
Effects
Refactoring Login
$.ajax('/login', { data: form, dataType: 'script', type: 'post'});
Successful login returns
$('#login').fadeOut(
$( ).html(...).fadeIn('slow');
2000);
'#login'
Effects
Adding a Queue
Successful login returns
$('#confirm .confirm-purchase').slideDown(500, 'linear'); $("...").css({'background-color': '#2C1F11', 'opacity':'0.5'}) .animate({ opacity: '1', height: '30'}, 'slow', 'linear');
$('#login').queue(function(next) { $(this).html("...").fadeIn('slow'); next();}); to dequeue the next item
Do the confirm box afterwards?
Effects
Adding a QueueDo the confirm box afterwards
$('#confirm .confirm-purchase').slideDown(500, 'linear'); $("...").css({'background-color': '#2C1F11', 'opacity':'0.5'}) .animate({ opacity: '1', height: '30'}, 'slow', 'linear');
$('#login').queue(function(next) { $(this).html("...").fadeIn('slow'
); next();});
, function() {
Effects
Improved Tool Tips
Let’s add fade in, out, and delayfunction showNumberOfFlights(e) {
var num_flights = $(this).data('flights');$(this).append("<span class='tooltip'>" + num_flights + " flights</span>");$("#tabs span.tooltip").show();
}
function hideNumberOfFlights(a) {$("#tabs span.tooltip").remove();
}
Effects
Improved Tool Tips
Let’s add fade in, out, and delayfunction showNumberOfFlights(e) {
var num_flights = $(this).data('flights');$(this).append("<span class='tooltip'>" + num_flights + " flights</span>");$("#tabs span.tooltip").
}
function hideNumberOfFlights(a) {$("#tabs span.tooltip")
.remove();
}
delay(300).fadeIn();
.fadeOut(function(){$(this)
});
Effects
Fixing the Delayfunction hideNumberOfFlights(a) {
$("#tabs span.tooltip").remove();
}
.fadeOut(function(){$(this)
});
.stop()
Will stop all effects
CODE ORGANIZATION
04 Encapsulating your Code
03 Creating Plugins
02 Creating Your Own Utility Functions
01 Each & Map Utility Functions
TABLE OF CONTENTS
05 Custom Events
06 jQuery Templates
Turning the Flight Function to JSON
Let’s receive JSON
fetchingFlights = $.ajax(' ', {/flights data: { date: activeDiv }, ... success: function(result) { $(activeDiv).html(result); $('#error').hide(); $(activeDiv).show(); } });}
CODE ORGANIZATION
The $.each Utility Function fetchingFlights = $.ajax(' ', {/flights data: { date: activeDiv }, ... success: function(result) {
.json
$(activeDiv + ' tbody td').remove();
var rows = "";$.each(flights, function(index, flight) {
});$(activeDiv + ' tbody').html(rows);...
rows += "<tr>" + <td>" + flight.depart + "</td>" + <td>" + flight.arrive + "</td>" + ... </tr>";
CODE ORGANIZATION
fetchingFlights = $.ajax(' ', {/flights data: { date: activeDiv }, ... success: function(result) {
.json
$(activeDiv + ' tbody td').remove();
});
...
"<tr>" + <td>" + flight.depart + "</td>" + <td>" + flight.arrive + "</td>" + ... </tr>";
var flight_rows = $.map(flights, function(flight) {return
$(activeDiv + ' tbody').html(flight_rows.join(''));
The $.map Utility Function
CODE ORGANIZATION
Extending jQuery (to stay DRY)
Not called on jQuery objects
Called on jQuery objects
Two ways to organize your code
Plugins
Utility Functions
$("#tabs ul li a").addToolTip();
$.filterFlights(json);
CODE ORGANIZATION
Creating Utility Functions
$.hello = function() { alert("Hello there!");};
$.hello();
CODE ORGANIZATION
(function( $ ){
})( jQuery );
Filter Based on Number of Stops
<div id="flight-filter"> <strong>Number of Stops</strong><br /> <input type="radio" name="stops" value="0" /> 0 Stops<br /> <input type="radio" name="stops" value="1" /> 0-1 Stops<br /> <input type="radio" name="stops" value="2+" checked="checked" /> 0-2+ Stops<br /></div>
$('#flight-filter input[name=stops]').change(filterByFlights);
When radio button changed
Filter Based on Number of Stops $('#flight-filter input[name=stops]').change(filterByFlights);
var stops = $(this).val();function filterByFlights(e) {
var filtered_flights = [];
$.each(currentFlights, function(index, flight) {if (stops == '2+') {
filtered_flights.push(flight); ... other conditionals ... }); ...reprint the flights... }
CODE ORGANIZATION
Create a Filter Utility Function $.filterFlights = function(cFlights, stops) {
var filtered_flights = [];
$.each(cFlights, function(index, flight) {if (stops == '2+') { filtered_flights.push(flight); ... other conditionals ...
});
return filtered_flights;};
var stops = $('#flight-filter input[name=stops]:checked').val();var filtered_flights = $.filterFlights(currentFlights, stops);
CODE ORGANIZATION
Creating Plugins
this
};
(function( $ ){
})( jQuery );
$(activeDiv).callOut();
Must call on a jQuery object
'fast');$.fn.callOut = function() {
.css({ opacity:0.5 }).animate({ opacity:1 },
CODE ORGANIZATION
Plugin Options with Defaults
this
};
$(activeDiv).callOut();
'fast'
) {$.fn.callOut = function(options
.css({ opacity:0.5 })
.animate({ opacity:1 },
var defaults = {duration:
}var options = $.extend(defaults, options);
options.duration);
$(activeDiv).callOut({'duration': 1000});
Use defaults, unless option exists
CODE ORGANIZATION
Creating Plugins
$("#tabs ul li a")mouseenter:
.bind({showNumberOfFlights,
mouseleave: hideNumberOfFlights});
function hideNumberOfFlights(e) {$("#tabs span.tooltip").stop().fadeOut(function(){
$(this).remove(); });}
function showNumberOfFlights(e) { var num_flights = $(this).data('flights'); $(this).append("..."); $("#tabs span.tooltip").delay(100).fadeIn();}
CODE ORGANIZATION
$("#tabs ul li a")
mouseenter:
mouseleave:
});
.stop().fadeOut(function(){$(this).remove();
});}
.delay(100).fadeIn();
}
$.fn.addToolTip = function() {return this.bind({
function(e) {var tip = $(this).data('tooltip');$("<span class='tooltip'>" + tip + "</span>")
.appendTo(this)},
function(e) {$(this).find('span.tooltip').
.addToolTip();
<li><a href="#2012-09-27" data-tooltip="6 flights">Sep 27</a></li><li><a href="#2012-09-28" data-tooltip="5 flights">Sep 28</a></li>
CODE ORGANIZATION
CODE ORGANIZATION
04 Encapsulating your Code
03 Creating Plugins
TABLE OF CONTENTS
05 Custom Events
06 jQuery Templates
02 Creating Your Own Utility Functions
01 Each & Map Utility Functions
Keeping Organized with Encapsulation varvar
fetchingFlightscurrentFlights
nullnull
;;=
=
functionfunctionfunction
functionfunction
showFlightschangeTabselectFlight
showTotallogin
{ .. }{ .. }
{ .. }
{ .. }{ .. }
(activeDiv)(e)
(e)
(e)(json)
$("#tabs ul li a").click(changeTab);
selectFlight);$("#tabs div").delegate('#flights a', 'click',
CODE ORGANIZATION
CODE ORGANIZATION
Keeping Organized with Encapsulation fetchingFlightscurrentFlights
nullnull
,,
functionfunction
function
functionfunction
showFlightschangeTabselectFlight
showTotallogin
(activeDiv)(e)
(e)
(e)(json)
{ .. }{ .. }
{ .. }
{ .. }{ .. }
selectFlights.init();
var confirmFlight = {
};
var selectFlights = {::
init : function() {
},:
::
::
};
$("#tabs ul li a").click(changeTab);
selectFlight);$("#tabs div").delegate('#flights a', 'click',
,,
,
CODE ORGANIZATION
Need to Specify the Object fetchingFlightscurrentFlights
nullnull
,,
functionfunction
function
functionfunction
showFlightschangeTabselectFlight
showTotallogin
(activeDiv)(e)
(e)
(e)(json)
{ .. }{ .. }
{ .. }
{ .. }{ .. }
selectFlights.init();
var confirmFlight = {
};
var selectFlights = {::
init : function() {
},:
::
::
};
$("#tabs ul li a").click( changeTab);selectFlights.
selectFlight);$("#tabs div").delegate('#flights a', 'click',
selectFlights.
,,
,
CODE ORGANIZATION
Can Also Use ‘this’ fetchingFlightscurrentFlights
nullnull
,,
functionfunction
function
functionfunction
showFlightschangeTabselectFlight
showTotallogin
(activeDiv)(e)
(e)
(e)(json)
{ .. }{ .. }
{ .. }
{ .. }{ .. }
selectFlights.init();
var confirmFlight = {
};
var selectFlights = {::
init : function() {
},:
::
::
};
$("#tabs ul li a").click( changeTab);this.
selectFlight);$("#tabs div").delegate('#flights a', 'click',
this.
,,
,
Allow Keys 1-5 To Select Tabs $(document).keydown(function(e) {if (e.keyCode >= 49 && e.keyCode <= 53) {
var numSelected = e.keyCode - 49;
// Select proper tab, switch classes, do ajax call }});
$("#tabs ul li:eq(" + numSelected + ") a");var tabSelected =
Our old tab click code$("#tabs ul li a").click(function(e) {
// Select proper tab, switch classes, do ajax call});
Let’s make it DRY!
CODE ORGANIZATION
Effects
Create a Custom Event & Trigger
// Select proper tab, switch classes, do ajax call
‘selectTab’ is our custom event// Select proper tab, switch classes, do ajax call
$("#tabs ul li a").bind({ 'selectTab': function(e) { }});
$(document).keydown(function(e) {if (e.keyCode >= 49 && e.keyCode <= 53) {
}});
$("#tabs ul li a").click(function(e) {
});
var numSelected = e.keyCode - 49;$("#tabs ul li:eq(" + tabSelected + ") a").trigger('selectTab');
$(this).trigger('selectTab');
fetchingFlights = $.ajax(' ', {/flights data: { date: activeDiv }, ... success: function(result) {
.json
$(activeDiv + ' tbody td').remove();
});
...
"<tr>" + <td>" + flight.depart + "</td>" + <td>" + flight.arrive + "</td>" + ... </tr>";
return
Remember This?
$(activeDiv + ' tbody') .html(flight_rows.join(''));
var flight_rows = $.map( , function(flight) {flights
CODE ORGANIZATION
});
YUCK! Tons of HTML in our JavaScript
return "<tr>" + "<td>" + flight.depart + "</td>" + "<td>" + flight.arrive + "</td>" + "<td>" + flight.flight + "</td>" + "<td>" + flight.routing + "</td>" + "<td><a href='#' data-flight='" + flight.flight + "' data-class='first_class'>" + flight.first_class + "</a></td>" + "<td><a href='#' data-flight='" + flight.flight + "' data-class='economy'>" + flight.economy + "</a></td>" + "</tr>";
$(activeDiv + ' tbody') .html(flight_rows.join(''));
var flight_rows = $.map( , function(flight) {flights
CODE ORGANIZATION
Using a Template
(activeDiv + ' tbody')flights$( "#flightTemplate" ).tmpl( )
.appendTo ;
<script id="flightTemplate" type="text/x-jquery-tmpl"> <tr> <td>${depart}</td> <td>${arrive}</td> <td>${flight}</td> <td>${routing}</td> <td><a href='#' data-flight='${flight}' data-class='first_class'> ${first_class}</a></td> <td><a href='#' data-flight='${flight}' data-class='economy'> ${economy}</a></td></tr></script>
flights is a JSON array
in our html
CODE ORGANIZATION
Including The Template Library
<script src="jquery.tmpl.js" type="text/javascript"></script>
Download & Documentationhttp://api.jquery.com/category/plugins/templates/
Include the Source
(at least until it’s baked in)
CODE ORGANIZATION
Using a Template<script id="flightTemplate" type="text/x-jquery-tmpl"> <tr> <td>${depart}</td> <td>${arrive}</td> <td>${flight}</td> <td>
{{if (routing == 0)}}Nonstop
{{else (routing == 1)}}1 Stop
{{else}}${routing} Stops
{{/if}} </td> ...</tr></script>
CODE ORGANIZATION