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
Sponsored
·
Ship Features Fearlessly
Turn features on and off without deploys. Used by thousands of Ruby developers.
→
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
540
fetch is the new XHR
othree
6
3.6k
Other Decks in Technology
See All in Technology
AI駆動開発が変える、大規模開発の前提 ーHuman in the Loop から Human on the Loop へ / AIE2026
visional_engineering_and_design
30
24k
チームで実践する AI-DLC 思考の軌跡を残すチェックポイント設計
belongadmin
0
3.2k
あなたの AI ワークスペースに、 専門コーダーを連れてくる - Amazon Quick Desktop 最新情報
kawaji_scratch
1
130
小さく始める AI 活用推進 ― 日経電子版 Web チームの事例/nikkei-tech-talk47
nikkei_engineer_recruiting
0
160
2026 TECHFRESH 畢業分享會 - AI-Native 重塑軟體工程與虛擬講師
line_developers_tw
PRO
0
650
就職⽀援サービスにおけるキャリアアドバイザーのシフトスケジューリング
recruitengineers
PRO
1
130
データサイエンスを価値につなげるプロジェクト設計 〜 DS一年目が現場で得た気づき 〜
ysd113
1
100
AI活用を推進するために ファインディが下した、一つの小さな決断
starfish719
0
300
FDE という解 ― 暗黙知と明示知をつなぐ、伴走型エンジニアリング ―
otanet
0
120
Socrates × Looker 〜セマンティックレイヤーで進化するデータ分析エージェント〜
hanon52_
3
2k
AIっぽい文章を採点して人間らしく直すアプリを作ってみた
yama3133
2
120
なぜ Platform Engineering の土台に Kubernetes を選ぶのか
r4ynode
1
560
Featured
See All Featured
Product Roadmaps are Hard
iamctodd
PRO
55
12k
How to Build an AI Search Optimization Roadmap - Criteria and Steps to Take #SEOIRL
aleyda
1
2.1k
sira's awesome portfolio website redesign presentation
elsirapls
0
280
BBQ
matthewcrist
89
10k
Six Lessons from altMBA
skipperchong
29
4.3k
Embracing the Ebb and Flow
colly
88
5.1k
We Are The Robots
honzajavorek
0
240
The Language of Interfaces
destraynor
162
27k
The Power of CSS Pseudo Elements
geoffreycrofte
82
6.3k
Scaling GitHub
holman
464
140k
Code Review Best Practice
trishagee
74
20k
Navigating Algorithm Shifts & AI Overviews - #SMXNext
aleyda
1
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