Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
jQuery Tool Objects
Search
Sponsored
·
Your Podcast. Everywhere. Effortlessly.
Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
→
othree
August 19, 2012
Technology
4.1k
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.5k
YAJS.vim and Vim Syntax Highlight
othree
1
3.1k
Web Trends to 2015
othree
4
370
Transducer
othree
9
3.2k
HITCON 11 Photographer
othree
4
550
fetch is the new XHR
othree
6
3.6k
Other Decks in Technology
See All in Technology
ASTを使って影響範囲を特定する
nealle
0
130
Code4Lib JAPANカンファレンス2026 開会挨拶 / Code4Lib JAPAN Conference 2026: Opening Remarks
ykiyota
0
270
現場に行くだけでは足りない——プロダクトエンジニアが業務の流れを捉える観点と、その鍛え方
takumiengineering
0
360
2026-09-10 【Snowflake World Tour Tokyo 2026】dbt Core と Snowflake で実現する多層的なデータガバナンス / Multi-Layered Data Governance Powered by dbt Core and Snowflake
civitaspo
0
270
プロダクトエンジニアに必要な「いい感じ」に作る能力 〜たくさん作れる時代に、どこまで作るかの決め方〜
jnishime_dresscode
2
1.4k
AI時代だからこそ、スケールしないことをやろう
yutashigemura
1
110
こんなアーキテクチャ図は嫌だ BEYOND THE TIME: 半年後の自分へ贈る15のメッセージ / 15 of Anti-pattern in AWS Architecture Diagrams
naospon
3
290
2026/09/10 Spring_Bootから_Jakarta_EE_MicroProfileへの移行
megascus
0
260
GoCon2026 - Open Source, Open World
sanposhiho
2
640
DEFCON_CHV_CTF_Write-up.pdf
bata_24
0
110
幾何アルゴリズムで なめらかなピン操作を / iOSDC Japan 2026 / smoothpin
kazumanagano
0
230
Multica × 長期記憶:40個のミニプロジェクト管理
eiei114
1
210
Featured
See All Featured
Test your architecture with Archunit
thirion
2
2.4k
Reality Check: Gamification 10 Years Later
codingconduct
0
2.3k
The World Runs on Bad Software
bkeepers
PRO
72
12k
Accessibility Awareness
sabderemane
1
200
Fight the Zombie Pattern Library - RWD Summit 2016
marcelosomers
234
17k
How to Get Subject Matter Experts Bought In and Actively Contributing to SEO & PR Initiatives.
livdayseo
0
190
The Success of Rails: Ensuring Growth for the Next 100 Years
eileencodes
47
8.3k
Optimising Largest Contentful Paint
csswizardry
37
3.9k
The Cost Of JavaScript in 2023
addyosmani
55
10k
Put a Button on it: Removing Barriers to Going Fast.
kastner
60
4.6k
Public Speaking Without Barfing On Your Shoes - THAT 2023
reverentgeek
1
560
jQuery: Nuts, Bolts and Bling
dougneiner
66
8.6k
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