Slide 1

Slide 1 text

jQuery Tool Objects othree@COSCUP

Slide 2

Slide 2 text

Tools • Queue • Deferred • Callbacks

Slide 3

Slide 3 text

queue http://www.flickr.com/photos/hktang/4243300265/

Slide 4

Slide 4 text

Timer • setTimeout • setInterval

Slide 5

Slide 5 text

http://ejohn.org/blog/how-javascript-timers-work/

Slide 6

Slide 6 text

Timer Issues • Timer not reliable • Race Condition between intervals

Slide 7

Slide 7 text

Ideal setTimeout left +=10 left +=10 left +=10 left +=10 left +=10 10ms 20ms 30ms 40ms 50ms

Slide 8

Slide 8 text

Real World left +=10 left +=10 left +=10 left +=10 left +=10 10ms 25ms 41ms 53ms 68ms

Slide 9

Slide 9 text

Smooth Animation • Get time period on every call

Slide 10

Slide 10 text

Smooth~ left +=10 left +=15 left +=16 left +=12 left +=15 10ms 25ms 41ms 53ms 68ms

Slide 11

Slide 11 text

Libraries • Library can make smooth animation

Slide 12

Slide 12 text

Race Condition • We want to fade something out then fade it in

Slide 13

Slide 13 text

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1

Slide 14

Slide 14 text

var fadeOut = function (target) {! target.style.opacity -= 0.1;! if (target.style.opacity > 0) {! setTimeout(fadeIn, 10);! }! };! ! var fadeIn = function (target) {! target.style.opacity += 0.1;! if (target.style.opacity < 1) {! setTimeout(fadeIn, 10);! }! };

Slide 15

Slide 15 text

var info = document.getElementById('info');! ! fadeOut(info);! fadeIn(info);

Slide 16

Slide 16 text

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1

Slide 17

Slide 17 text

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1

Slide 18

Slide 18 text

... • Not fade in • Infinity loop • If we use time period on each call • Not infinity loop • Animation is ugly

Slide 19

Slide 19 text

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1

Slide 20

Slide 20 text

Solution • Callback function

Slide 21

Slide 21 text

Callback $('#info').fadeOut(function () {! $(this).fadeIn();! });

Slide 22

Slide 22 text

jQuery fade $('#info').fadeOut();! $('#info').fadeIn();

Slide 23

Slide 23 text

The Queue • Traditional queue • Solves race condition

Slide 24

Slide 24 text

.queue() $('#info').queue('qName', function () {! //things to do next! ! $(this).dequeue();! });

Slide 25

Slide 25 text

Animate and Queue • .animate always use ‘fx’ as its queue name • .queue has default queue name: ‘fx’

Slide 26

Slide 26 text

If Boss Want • Fade Out • Change content • Fade In • Move right 500 pixel • Add class ‘active’ • Move left 500 pixel • Change content again

Slide 27

Slide 27 text

Callbacks $('#id').fadeOut(function () {! $(this).html('new content');! $(this).fadeIn(function () {! $(this).animate({left: '+=500'}, function () {! $(this).addClass('active');! $(this).animate({left: '-=500'}, function () {! $(this).html('even new content');! });! });! });! });

Slide 28

Slide 28 text

Queue $('#id')! .fadeOut()! .queue(function () {! $(this).html('new content');! $(this).dequeue();! })! .fadeIn()! .animate({left: '+=500'})! .queue(function () {! $(this).addClass('active');! $(this).dequeue();! })! .animate({left: '-=500'})! .queue(function () {! $(this).html('even new content');! $(this).dequeue();! });

Slide 29

Slide 29 text

Advantages • Less indent • Delay or clear queue is much easier • Better for maintain • What happens if boss want to change spec

Slide 30

Slide 30 text

If I Want To • Fade out A, B, C by order

Slide 31

Slide 31 text

$('#A').fadeOut();! $('#B').fadeOut();! $('#C').fadeOut(); W rong

Slide 32

Slide 32 text

$('#A').fadeOut(function () {! $('#B').fadeOut(function () {! $('#C').fadeOut();! });! });

Slide 33

Slide 33 text

$('#A')! .fadeOut()! .queue(function () {! var $that = $(this);! $('#B').fadeOut(function () {! $that.dequeue();! });! })! .queue(function () {! var $that = $(this);! $('#C').fadeOut(function () {! $that.dequeue();! });! });

Slide 34

Slide 34 text

$({}).queue(function () {! var $that = $(this);! $('#A').fadeOut(function () {! $that.dequeue();! });! }).queue(function () {! var $that = $(this);! $('#B').fadeOut(function () {! $that.dequeue();! });! }).queue(function () {! var $that = $(this);! $('#C').fadeOut(function () {! $that.dequeue();! });! });

Slide 35

Slide 35 text

$({}).queue(function (next) {! $('#A').fadeOut(next);! }).queue(function (next) {! $('#B').fadeOut(next);! }).queue(function (next) {! $('#C').fadeOut(next);! });

Slide 36

Slide 36 text

$('#A').fadeOut().queue(function (next) {! $('#B').fadeOut(next);! }).queue(function (next) {! $('#C').fadeOut(next);! });

Slide 37

Slide 37 text

Deferred http://www.flickr.com/photos/gozalewis/3256814461/

Slide 38

Slide 38 text

History • a.k.a Promise • Idea since 1976 (Call by future) • Dojo 0.9 (2007), 1.5 (2010) • jQuery 1.5 (2011) • CommonJS Promises/A

Slide 39

Slide 39 text

What is Deferred • In computer science, future, promise, and delay refer to constructs used for synchronization in some concurrent programming languages. http://en.wikipedia.org/wiki/Futures_and_promises

Slide 40

Slide 40 text

login get account render page redirect tell result tell result tell result

Slide 41

Slide 41 text

get account render page redirect login status wait result wait result wait result

Slide 42

Slide 42 text

login get account render page redirect Deferred wait result wait result wait result tell result

Slide 43

Slide 43 text

login get account render page redirect Deferred register handler register handler register handler change status

Slide 44

Slide 44 text

login get account render page redirect Deferred resolve reject fail done fail done fail done $.Deferred()

Slide 45

Slide 45 text

jQuery Deferred • Multiple handler functions • Register handlers at any time • jQuery.when http://api.jquery.com/category/deferred-object/

Slide 46

Slide 46 text

Example: Image Loader function imgLoader(src) {! var _img = new Image(),! _dfd = $.Deferred();! ! _img.onload = _dfd.resolve; //success! _img.onerror = _dfd.reject; //fail! ! _img.src = src! ! return _dfd.promise();! }

Slide 47

Slide 47 text

login get account render page redirect Deferred resolve reject fail done fail done fail done

Slide 48

Slide 48 text

Image Loader image fade out image render page Deferred

Slide 49

Slide 49 text

render page image Deferred .promise() resolve reject fade out image fail done Image Loader

Slide 50

Slide 50 text

Use Image Loader imgLoader('/images/logo.png').done(function () {! ! $('#logo').fadeIn();! ! }).fail(function () {! ! document.location = '/404.html';! ! });

Slide 51

Slide 51 text

Use Image Loader var logo_dfd = imgLoader('/images/logo.png');! ! logo_dfd.done(function () {! $('#logo').fadeIn();! }).fail(function () {! document.location = '/404.html';! });! ! //Some place else! logo_dfd.done(function () {! App.init();! });! ! //Another place ! logo_dfd.fail(function () {! App.destroy();! });

Slide 52

Slide 52 text

jQuery.when $.when(! ! $.getJSON('/api/jedis'),! $.getJSON('/api/siths'),! $.getJSON('/api/terminators')! ! ).done(function (jedis, siths, terminators) {! ! // do something....! ! });

Slide 53

Slide 53 text

Complex Dependency data device async async render account async

Slide 54

Slide 54 text

var account = $.getJSON('/api/account');! var device = account.pipe(function () {! $.getJSON('/api/device');! });! ! var data = $.when(account, device).pipe(function () {! $.getJSON('/api/data');! });! ! $.when(account, device, data).done(render);

Slide 55

Slide 55 text

Advantages • Manage handlers • Cache results • $.when solves complex async dependency

Slide 56

Slide 56 text

Advance Feature • pipe

Slide 57

Slide 57 text

Not to Talk Today

Slide 58

Slide 58 text

Callbacks http://www.flickr.com/photos/inkytwist/3708782412/

Slide 59

Slide 59 text

Callbacks • A multi-purpose callbacks list object that provides a powerful way to manage callback lists

Slide 60

Slide 60 text

How to Use function fn( value ){! console.log( value );! }! ! var callbacks = $.Callbacks();! callbacks.add( fn );! callbacks.fire( "foo!" );

Slide 61

Slide 61 text

Methods • add • remove • has • fire • fireWith • fired • lock • locked • disable • disabled • empty

Slide 62

Slide 62 text

Flags • once • memory • unique • stopOnFalse

Slide 63

Slide 63 text

once • Can only be fired once

Slide 64

Slide 64 text

once function fn1( value ) {! console.log( value );! }! ! var callbacks = $.Callbacks('once');! callbacks.add( fn1 );! callbacks.fire( "foo!" ); // foo!! callbacks.fire( "foo!" ); //

Slide 65

Slide 65 text

memory • Remember the arguments you give

Slide 66

Slide 66 text

memory function fn1( value ) {! console.log( value );! }! function fn2() {! console.log( '2' );! }! ! var callbacks = $.Callbacks('memory');! callbacks.add( fn1 );! callbacks.fire( "foo!" ); // foo!! callbacks.add( fn1 ); // foo!! callbacks.add( fn2 ); // 2! callbacks.fire( "bar!" ); // bar!, bar!, 2

Slide 67

Slide 67 text

once memory function fn1( value ) {! console.log( value );! }! function fn2() {! console.log( '2' );! }! ! var callbacks = $.Callbacks('once memory');! callbacks.add( fn1 );! callbacks.fire( "foo!" ); // foo!! callbacks.add( fn1 ); // foo!! callbacks.add( fn2 ); // 2! callbacks.fire( "bar!" ); //

Slide 68

Slide 68 text

unique • Ensure all callback function are unique

Slide 69

Slide 69 text

unique function fn1( value ) {! console.log( value );! }! function fn2() {! console.log( '2' );! }! ! var callbacks = $.Callbacks('unique');! callbacks.add( fn1 );! callbacks.add( fn1 ); ! callbacks.add( fn2 );! callbacks.fire( "foo!" ); // foo!, 2

Slide 70

Slide 70 text

stopOnFalse • Stop if a function returns false

Slide 71

Slide 71 text

Deferred • Use ‘once memory’

Slide 72

Slide 72 text

When to Use • If you have to manage callback functions • If you need any feature of the flags • If you want to break down your codes

Slide 73

Slide 73 text

Use Case • jQuery Deferred Object • PubSub by Addy Osmani

Slide 74

Slide 74 text

Questions?

Slide 75

Slide 75 text

PubSub var topics = {};! ! jQuery.Topic = function( id ) {! var callbacks,! topic = id && topics[ id ];! if ( !topic ) {! callbacks = jQuery.Callbacks();! topic = {! publish: callbacks.fire,! subscribe: callbacks.add,! unsubscribe: callbacks.remove! };! if ( id ) {! topics[ id ] = topic;! }! }! return topic;! }; http://addyosmani.com/blog/jquery-1-7s-callbacks-feature-demystified/

Slide 76

Slide 76 text

References • http://api.jquery.com/queue/ • http://api.jquery.com/category/deferred-object/ • http://api.jquery.com/jQuery.Callbacks/ • http://addyosmani.com/blog/jquery-1-7s-callbacks- feature-demystified/

Slide 77

Slide 77 text

Thank You