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.2k
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
530
fetch is the new XHR
othree
6
3.6k
Other Decks in Technology
See All in Technology
2026TECHFRESH畢業分享會 - Lightning Talk - E起 See See : 電商推薦讀心術? 數據說了算
line_developers_tw
PRO
0
520
Oracle Cloud Infrastructure IaaS 新機能アップデート 2026/3 - 2026/5
oracle4engineer
PRO
1
240
「嘘をつくテスト」の失敗例から学ぶ 良いテストコード #frontend_phpcon_do
asumikam
0
610
Reliability in the Age of AI: Engineering for AI Velocity
rrreeeyyy
0
120
AIソロプレナー時代に2ヶ月で20人増員した事業創造会社の開発組織の話
miyatakoji
0
510
なぜ Platform Engineering の土台に Kubernetes を選ぶのか
r4ynode
1
510
日本 Fintech 未来予測レポート 2027〜2028年(オリジナル版)
8maki
0
270
新しいVibe Codingと”自走”について
watany
5
270
AIっぽい文章を採点して人間らしく直すアプリを作ってみた
yama3133
2
110
Disciplined Vibes: Scaling AI-Assisted Engineering
sheharyar
0
110
10倍の生産性を実現するAI駆動並列エージェントのすべて
kumaiu
4
1.3k
チームで実践する AI-DLC 思考の軌跡を残すチェックポイント設計
belongadmin
0
3.2k
Featured
See All Featured
Amusing Abliteration
ianozsvald
1
200
Unsuck your backbone
ammeep
672
58k
Visualizing Your Data: Incorporating Mongo into Loggly Infrastructure
mongodb
49
10k
Claude Code どこまでも/ Claude Code Everywhere
nwiizo
65
56k
Bash Introduction
62gerente
615
210k
WENDY [Excerpt]
tessaabrams
11
38k
Getting science done with accelerated Python computing platforms
jacobtomlinson
2
220
Designing Dashboards & Data Visualisations in Web Apps
destraynor
231
55k
Ethics towards AI in product and experience design
skipperchong
2
310
Design in an AI World
tapps
1
230
AI: The stuff that nobody shows you
jnunemaker
PRO
8
700
AI in Enterprises - Java and Open Source to the Rescue
ivargrimstad
0
1.3k
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