Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
jQuery Tool Objects
Search
othree
August 19, 2012
Technology
4k
7
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
jQuery Tool Objects
othree
August 19, 2012
More Decks by othree
See All by othree
How GitHub Supports Vim License Detection, The Five Years Journey
othree
1
2.3k
WAT JavaScript Date
othree
3
2.2k
Modern HTML Email Development
othree
3
2.8k
MRT & GIT
othree
1
2.4k
YAJS.vim and Vim Syntax Highlight
othree
1
3.1k
Web Trends to 2015
othree
4
360
Transducer
othree
9
3.2k
HITCON 11 Photographer
othree
4
540
fetch is the new XHR
othree
6
3.6k
Other Decks in Technology
See All in Technology
研究開発部の紹介 / Sansan R&D Profile
sansan33
PRO
4
24k
Sets in Go
ramalho
1
880
その“隠したつもり”が命取り ── 自前と平文をやめて「正解」に委ねる
kuroneko13
0
130
ボトムアップ文化が強い組織で セキュリティをどう根付かせていくかの現在進行形の話 / Making Security Stick in a Bottom-Up Organization
yamaguchitk333
0
240
私がブラウザを自作したくなった理由
supurazako
1
240
なぜ Temporal の大小比較には compare しかないのか / Why Does Temporal Only Have compare() for Comparisons
kazukihayase
1
140
会社紹介資料 / Sansan Company Profile
sansan33
PRO
24
430k
AIペネトレーションテスト・ セキュリティ検証「AgenticSec」紹介資料
laysakura
2
9.1k
Eight Engineering Unit 紹介資料
sansan33
PRO
3
8.2k
制約理論(ToC)入門 2026版
recruitengineers
PRO
8
2.4k
トヨタ⽣産⽅式(TPS)⼊⾨
recruitengineers
PRO
3
920
『三匹の子ぶた』から学ぶネットワークセキュリティの昔と今 / Network Security: Then and Now Through the Lens of The Three Little Pigs
nttcom
1
6.2k
Featured
See All Featured
Scaling GitHub
holman
464
140k
Done Done
chrislema
186
16k
Optimising Largest Contentful Paint
csswizardry
37
3.9k
Building Adaptive Systems
keathley
44
3.2k
How to train your dragon (web standard)
notwaldorf
97
6.8k
AI in Enterprises - Java and Open Source to the Rescue
ivargrimstad
0
1.4k
How to Align SEO within the Product Triangle To Get Buy-In & Support - #RIMC
aleyda
2
1.8k
Introduction to Domain-Driven Design and Collaborative software design
baasie
1
940
Imperfection Machines: The Place of Print at Facebook
scottboms
270
14k
4 Signs Your Business is Dying
shpigford
187
23k
Understanding Cognitive Biases in Performance Measurement
bluesmoon
32
3k
Applied NLP in the Age of Generative AI
inesmontani
PRO
4
2.4k
Transcript
jQuery Tool Objects othree@COSCUP
Tools • Queue • Deferred • Callbacks
queue http://www.flickr.com/photos/hktang/4243300265/
Timer • setTimeout • setInterval
http://ejohn.org/blog/how-javascript-timers-work/
Timer Issues • Timer not reliable • Race Condition between
intervals
Ideal setTimeout left +=10 left +=10 left +=10 left +=10
left +=10 10ms 20ms 30ms 40ms 50ms
Real World left +=10 left +=10 left +=10 left +=10
left +=10 10ms 25ms 41ms 53ms 68ms
Smooth Animation • Get time period on every call
Smooth~ left +=10 left +=15 left +=16 left +=12 left
+=15 10ms 25ms 41ms 53ms 68ms
Libraries • Library can make smooth animation
Race Condition • We want to fade something out then
fade it in
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9
1
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);! }! };
var info = document.getElementById('info');! ! fadeOut(info);! fadeIn(info);
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9
1
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9
1
... • Not fade in • Infinity loop • If
we use time period on each call • Not infinity loop • Animation is ugly
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9
1
Solution • Callback function
Callback $('#info').fadeOut(function () {! $(this).fadeIn();! });
jQuery fade $('#info').fadeOut();! $('#info').fadeIn();
The Queue • Traditional queue • Solves race condition
.queue() $('#info').queue('qName', function () {! //things to do next! !
$(this).dequeue();! });
Animate and Queue • .animate always use ‘fx’ as its
queue name • .queue has default queue name: ‘fx’
If Boss Want • Fade Out • Change content •
Fade In • Move right 500 pixel • Add class ‘active’ • Move left 500 pixel • Change content again
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');! });! });! });! });
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();! });
Advantages • Less indent • Delay or clear queue is
much easier • Better for maintain • What happens if boss want to change spec
If I Want To • Fade out A, B, C
by order
$('#A').fadeOut();! $('#B').fadeOut();! $('#C').fadeOut(); W rong
$('#A').fadeOut(function () {! $('#B').fadeOut(function () {! $('#C').fadeOut();! });! });
$('#A')! .fadeOut()! .queue(function () {! var $that = $(this);! $('#B').fadeOut(function
() {! $that.dequeue();! });! })! .queue(function () {! var $that = $(this);! $('#C').fadeOut(function () {! $that.dequeue();! });! });
$({}).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();! });! });
$({}).queue(function (next) {! $('#A').fadeOut(next);! }).queue(function (next) {! $('#B').fadeOut(next);! }).queue(function (next)
{! $('#C').fadeOut(next);! });
$('#A').fadeOut().queue(function (next) {! $('#B').fadeOut(next);! }).queue(function (next) {! $('#C').fadeOut(next);! });
Deferred http://www.flickr.com/photos/gozalewis/3256814461/
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
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
login get account render page redirect tell result tell result
tell result
get account render page redirect login status wait result wait
result wait result
login get account render page redirect Deferred wait result wait
result wait result tell result
login get account render page redirect Deferred register handler register
handler register handler change status
login get account render page redirect Deferred resolve reject fail
done fail done fail done $.Deferred()
jQuery Deferred • Multiple handler functions • Register handlers at
any time • jQuery.when http://api.jquery.com/category/deferred-object/
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();! }
login get account render page redirect Deferred resolve reject fail
done fail done fail done
Image Loader image fade out image render page Deferred
render page image Deferred .promise() resolve reject fade out image
fail done Image Loader
Use Image Loader imgLoader('/images/logo.png').done(function () {! ! $('#logo').fadeIn();! ! }).fail(function
() {! ! document.location = '/404.html';! ! });
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();! });
jQuery.when $.when(! ! $.getJSON('/api/jedis'),! $.getJSON('/api/siths'),! $.getJSON('/api/terminators')! ! ).done(function (jedis, siths,
terminators) {! ! // do something....! ! });
Complex Dependency data device async async render account async
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);
Advantages • Manage handlers • Cache results • $.when solves
complex async dependency
Advance Feature • pipe
Not to Talk Today
Callbacks http://www.flickr.com/photos/inkytwist/3708782412/
Callbacks • A multi-purpose callbacks list object that provides a
powerful way to manage callback lists
How to Use function fn( value ){! console.log( value );!
}! ! var callbacks = $.Callbacks();! callbacks.add( fn );! callbacks.fire( "foo!" );
Methods • add • remove • has • fire •
fireWith • fired • lock • locked • disable • disabled • empty
Flags • once • memory • unique • stopOnFalse
once • Can only be fired once
once function fn1( value ) {! console.log( value );! }!
! var callbacks = $.Callbacks('once');! callbacks.add( fn1 );! callbacks.fire( "foo!" ); // foo!! callbacks.fire( "foo!" ); //
memory • Remember the arguments you give
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
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!" ); //
unique • Ensure all callback function are unique
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
stopOnFalse • Stop if a function returns false
Deferred • Use ‘once memory’
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
Use Case • jQuery Deferred Object • PubSub by Addy
Osmani
Questions?
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/
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/
Thank You