$30 off During Our Annual Pro Sale. View Details »

jQuery Tool Objects

othree
August 19, 2012

jQuery Tool Objects

othree

August 19, 2012
Tweet

More Decks by othree

Other Decks in Technology

Transcript

  1. jQuery Tool Objects othree@COSCUP

  2. Tools • Queue • Deferred • Callbacks

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

  4. Timer • setTimeout • setInterval

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

  6. Timer Issues • Timer not reliable • Race Condition between

    intervals
  7. Ideal setTimeout left +=10 left +=10 left +=10 left +=10

    left +=10 10ms 20ms 30ms 40ms 50ms
  8. Real World left +=10 left +=10 left +=10 left +=10

    left +=10 10ms 25ms 41ms 53ms 68ms
  9. Smooth Animation • Get time period on every call

  10. Smooth~ left +=10 left +=15 left +=16 left +=12 left

    +=15 10ms 25ms 41ms 53ms 68ms
  11. Libraries • Library can make smooth animation

  12. Race Condition • We want to fade something out then

    fade it in
  13. 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9

    1
  14. 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);! }! };
  15. var info = document.getElementById('info');! ! fadeOut(info);! fadeIn(info);

  16. 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9

    1
  17. 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9

    1
  18. ... • Not fade in • Infinity loop • If

    we use time period on each call • Not infinity loop • Animation is ugly
  19. 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9

    1
  20. Solution • Callback function

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

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

  23. The Queue • Traditional queue • Solves race condition

  24. .queue() $('#info').queue('qName', function () {! //things to do next! !

    $(this).dequeue();! });
  25. Animate and Queue • .animate always use ‘fx’ as its

    queue name • .queue has default queue name: ‘fx’
  26. If Boss Want • Fade Out • Change content •

    Fade In • Move right 500 pixel • Add class ‘active’ • Move left 500 pixel • Change content again
  27. 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');! });! });! });! });
  28. 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();! });
  29. Advantages • Less indent • Delay or clear queue is

    much easier • Better for maintain • What happens if boss want to change spec
  30. If I Want To • Fade out A, B, C

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

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

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

    () {! $that.dequeue();! });! })! .queue(function () {! var $that = $(this);! $('#C').fadeOut(function () {! $that.dequeue();! });! });
  34. $({}).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();! });! });
  35. $({}).queue(function (next) {! $('#A').fadeOut(next);! }).queue(function (next) {! $('#B').fadeOut(next);! }).queue(function (next)

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

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

  38. 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
  39. 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
  40. login get account render page redirect tell result tell result

    tell result
  41. get account render page redirect login status wait result wait

    result wait result
  42. login get account render page redirect Deferred wait result wait

    result wait result tell result
  43. login get account render page redirect Deferred register handler register

    handler register handler change status
  44. login get account render page redirect Deferred resolve reject fail

    done fail done fail done $.Deferred()
  45. jQuery Deferred • Multiple handler functions • Register handlers at

    any time • jQuery.when http://api.jquery.com/category/deferred-object/
  46. 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();! }
  47. login get account render page redirect Deferred resolve reject fail

    done fail done fail done
  48. Image Loader image fade out image render page Deferred

  49. render page image Deferred .promise() resolve reject fade out image

    fail done Image Loader
  50. Use Image Loader imgLoader('/images/logo.png').done(function () {! ! $('#logo').fadeIn();! ! }).fail(function

    () {! ! document.location = '/404.html';! ! });
  51. 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();! });
  52. jQuery.when $.when(! ! $.getJSON('/api/jedis'),! $.getJSON('/api/siths'),! $.getJSON('/api/terminators')! ! ).done(function (jedis, siths,

    terminators) {! ! // do something....! ! });
  53. Complex Dependency data device async async render account async

  54. 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);
  55. Advantages • Manage handlers • Cache results • $.when solves

    complex async dependency
  56. Advance Feature • pipe

  57. Not to Talk Today

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

  59. Callbacks • A multi-purpose callbacks list object that provides a

    powerful way to manage callback lists
  60. How to Use function fn( value ){! console.log( value );!

    }! ! var callbacks = $.Callbacks();! callbacks.add( fn );! callbacks.fire( "foo!" );
  61. Methods • add • remove • has • fire •

    fireWith • fired • lock • locked • disable • disabled • empty
  62. Flags • once • memory • unique • stopOnFalse

  63. once • Can only be fired once

  64. once function fn1( value ) {! console.log( value );! }!

    ! var callbacks = $.Callbacks('once');! callbacks.add( fn1 );! callbacks.fire( "foo!" ); // foo!! callbacks.fire( "foo!" ); //
  65. memory • Remember the arguments you give

  66. 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
  67. 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!" ); //
  68. unique • Ensure all callback function are unique

  69. 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
  70. stopOnFalse • Stop if a function returns false

  71. Deferred • Use ‘once memory’

  72. 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
  73. Use Case • jQuery Deferred Object • PubSub by Addy

    Osmani
  74. Questions?

  75. 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/
  76. 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/

  77. Thank You