json part 3: asynchronous ajax & jquery deferred

33
BUILT IN FAIRFIELD COUNTY: FRONT END DEVELOPERS MEETUP TUES. JULY 9, 2013 JSON Part 3: Asynchronous Ajax and JQuery Deferred

Upload: jeff-fox

Post on 12-Nov-2014

5.870 views

Category:

Technology


5 download

DESCRIPTION

The final slides from the BFIC Deep Dive into JSON series. This deck covers an introduction to asynchronous operations and how to handle them using the JQuery Deferred object.

TRANSCRIPT

Page 1: JSON Part 3: Asynchronous Ajax & JQuery Deferred

BUILT IN FAIRFIELD COUNTY: FRONT END DEVELOPERS MEETUP

TUES. JULY 9, 2013

JSON Part 3: Asynchronous Ajax and JQuery Deferred

Page 2: JSON Part 3: Asynchronous Ajax & JQuery Deferred

About Jeff Fox (@jfox015)

16 year web development professional

(Almost) entirely self taught

Thorough front and back end experience

Develops JavaScript based web apps that rely on JSON and Ajax for data workflow

Page 3: JSON Part 3: Asynchronous Ajax & JQuery Deferred

Overview

JSON and Ajax Review

Asynchronous operations

The Deferred Pattern

Using Deferred with JQuery

Live Demo

Final Wrap Up

Page 4: JSON Part 3: Asynchronous Ajax & JQuery Deferred

JSON and Ajax Review

Page 5: JSON Part 3: Asynchronous Ajax & JQuery Deferred

JSON Highlights

A lightweight text based data interchange format

Use it to transfer JavaScript object data to and from a remote data source

Language independent

Based on a subset of the JavaScript Programming Language

Easy to understand, manipulate and generate

Page 6: JSON Part 3: Asynchronous Ajax & JQuery Deferred

Ajax Highlights

Ajax is “Asynchronous JavaScript and XML”

JavaScript API for exchanging data with a web server and returning the response to JavaScript

First created by Microsoft before being standardized by the open source community and W3C

Faster data exchange than sending and loading full web pages

Can either make for a better user experience or hinder it

Page 7: JSON Part 3: Asynchronous Ajax & JQuery Deferred

Onto Asynchronous operations

Page 8: JSON Part 3: Asynchronous Ajax & JQuery Deferred

Asynchronous operations are…

Operations that occur without a regular or predictable time relationship to a specified event such as a mouse click or time interval

Often times unpredictablewhen used on the Web

Linear functions within a scriptwill may be executed even before the Ajax operation has responded

Page 9: JSON Part 3: Asynchronous Ajax & JQuery Deferred

Examples of Asynchronous operations

Function Callbacks

Animations

Polling

External Data Calls (Ajax)

User Events

Page 10: JSON Part 3: Asynchronous Ajax & JQuery Deferred

The Deferred Pattern and Promises/A

Page 11: JSON Part 3: Asynchronous Ajax & JQuery Deferred

No…Not that kind of pattern

Page 12: JSON Part 3: Asynchronous Ajax & JQuery Deferred

The Deferred Design Pattern

Describes an object which acts as a proxy for a process or action that may or may not have completed

Can be applied to any asynchronous process such as AJAX requests, scripted animations, or web workers

Allows you to specify what will occur when the delayed process either completes or fails

Helps to abstract away the "when" part of your asynchronous processes

Page 13: JSON Part 3: Asynchronous Ajax & JQuery Deferred

Promises/A

A open spec created to simply detail the expected functionality of then() functions.

A guide for developers and JS lib creators to build common and cohesive then() support

JQuery 1.9.1 currently does not provide full support for this spec as written

Page 14: JSON Part 3: Asynchronous Ajax & JQuery Deferred

Using Deferred with JQuery

Page 15: JSON Part 3: Asynchronous Ajax & JQuery Deferred

Old method for handling Ajax Requests

$.ajax({ url: "/aphppage.php", success: function() { // handle success }, error: function() { // handle error });

Page 16: JSON Part 3: Asynchronous Ajax & JQuery Deferred

The JQuery Deferred object

Allows multiple listeners to Ajax events without manually chaining callbacks

Can be manually created via the $.Deferred() method

Can register callback functions if deferred resolves successfully, is rejected or notify of progress towards a resolved state

Can be passed around indefinitely

Callbacks can continue to be added during the entire lifetime of the deferred object, even if it is in a resolved state

Page 17: JSON Part 3: Asynchronous Ajax & JQuery Deferred

More JQuery Deferred

Starts out in a Pending state. Can only be resolved once in lifecycle.

Calls all listeners immediately (albeit asynchronously) once it is resolved.

Will execute any new callbacks immediately if it is resolved.

Page 18: JSON Part 3: Asynchronous Ajax & JQuery Deferred

Ajax Resolution and Rejection

JQuery's ajax() method will call resolve() on the deferred it returns when the request completes successfully, and reject() if the request fails (for example, a 404 HTTP response).

resolve() and reject() can also be manually executed on any manually created Deferred object

Page 19: JSON Part 3: Asynchronous Ajax & JQuery Deferred

The JQuery Deferred Promise

A Promise is a read-only JQuery Deferred object

These are returned by default by all JQuery Ajax methods

They give us back functional composition and error bubbling in the asynchronous world

Page 20: JSON Part 3: Asynchronous Ajax & JQuery Deferred

Handling completed promises

done() is the default callback for handling a successful Ajax operation

$.get(url).done(function(){ alert(“Operation done.”); });

fail() is the default handler for operations that are rejected.

$.get(url).done(function(){ alert(“Operation done.”); }).fail(function(){ alert(“Operation failed.”); });

Page 21: JSON Part 3: Asynchronous Ajax & JQuery Deferred

Handling completed promises

always() executed regardless of whether done or fail are completed

$.get(“someurl.php”).done(function(){ alert(“Operation done.”); }).fail(function(){ alert(“Operation failed.”); }).always(function() { alert(“Operations complete.”});

Page 22: JSON Part 3: Asynchronous Ajax & JQuery Deferred

Handling completed promises

Multiple callbacks can be assigned to Deferred objects

Callbacks are executed in the order they were added.

Page 23: JSON Part 3: Asynchronous Ajax & JQuery Deferred

Handling multiple deferred operations

$.when() accepts one or more promises and produces a new promise that will only resolve when all the supplied objects have completed or failed

If a single argument is passed that is not a Deferred or Promise, it will be treated as a resolved Deferred and any callbacks will be executed immediately var emp_def = $.get(“employees”),loc_def = $.get(“locations”);$.when(emp_def, loc_def).done(function(emp_resp, loc_resp){ alert(“Operations done.”); });

Page 24: JSON Part 3: Asynchronous Ajax & JQuery Deferred

Handling multiple deferred operations

$.then() adds handlers to be called when the Deferred object is resolved, rejected, or still in progress.

As of JQuery 1.8, returns a new promise that can filter the status and values of a deferred through a function

Replaces the deprecated pipe() function

Page 25: JSON Part 3: Asynchronous Ajax & JQuery Deferred

Simple Then example

when(

promise1,

promise2,

...

).then(function( futureValue1, futureValue2, ... ){

/* all promises have completed successfully */

}, function(){

/* error(s) occurred*/

});

Page 26: JSON Part 3: Asynchronous Ajax & JQuery Deferred

Notifying Deferred Objects

JQuery 1.7+ includes the concept of progress to a deferred

progress() allows you to attach callbacks that are executed when notify() is called on the deferred

This allows the deferred to represent the concept of progress towards a resolved state

Can be attached to long loading processes to update a progress bar, for example

Page 27: JSON Part 3: Asynchronous Ajax & JQuery Deferred

Live Examples

Page 28: JSON Part 3: Asynchronous Ajax & JQuery Deferred

Demos

Simple static Deferred execution examples

Deferred object applied to Dynamic App demo

Combining multiple Ajax calls with when() and then()

Page 29: JSON Part 3: Asynchronous Ajax & JQuery Deferred

Resources

JQuery Deferred API Spec:http://api.jquery.com/category/deferred-object/

An introduction to JQuery Deferred by Daniel Demmelhttp://danieldemmel.me/blog/2013/03/22/an-introduction-to-jquery-deferred-slash-promise/

Download Example Code:https://github.com/jfox015/BIFC-JSON-Deferred

Page 30: JSON Part 3: Asynchronous Ajax & JQuery Deferred

Resources

You're Missing the Point of Promises by Domenic Denicolahttp://domenic.me/2012/10/14/youre-missing-the-point-of-promises/

Making Promises With JQuery Deferred http://www.htmlgoodies.com/beyond/javascript/making-promises-with-jquery-deferred.html

Image Pre-loader using Deferred Object:https://gist.github.com/fcalderan/958683

Page 31: JSON Part 3: Asynchronous Ajax & JQuery Deferred

Resources

JS Libs with Promises/A support:

Q by Kris Kowal and Domenic Denicola: a full-featured promise library with a large, powerful API surface, adapters for Node.js, progress support, and preliminary support for long stack traces.

RSVP.js by Yehuda Katz: a very small and lightweight, but still fully compliant, promise library.

when.js by Brian Cavalier: an intermediate library with utilities for managing collections of eventual tasks, as well as support for both progress and cancellation.

Page 32: JSON Part 3: Asynchronous Ajax & JQuery Deferred

Questions?

Page 33: JSON Part 3: Asynchronous Ajax & JQuery Deferred