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
540
fetch is the new XHR
othree
6
3.6k
Other Decks in Technology
See All in Technology
ボーイスカウトルールでメモリやスキルを改善しよう
azukiazusa1
4
1.2k
「早く出す」より「事業に効く」 ── 顧客の業務サイクルから逆算するAI時代の二重ループ開発と「変化の設計者」 / devsumi2026
rakus_dev
1
260
プロダクトだけじゃない、社内プロセスにおける自動化・省力化ノススメ
kakehashi
PRO
1
3.8k
CSに"SLO"は要らない、経営層に"99.9%"は伝わらない - SREを全社に"翻訳"する3原則
cscengineer
PRO
1
4.6k
SRE依存からの脱却 運用を開 発チームへ移す、 フルサイ クル開 発体制の実践
joooee0000
0
2.8k
Type-safe IaC for Dart
coborinai
0
110
DMM.com 購入改善推進チーム におけるCodeRabbitを用いた レビューフロー改善の一例
ysknsid25
2
640
事業価値を⽣み出すSREへ SREが担うべき意思決定の5層
kenta_hi
2
3.7k
依頼文化をやめる日 EM視点で語るPlatform EngineeringとInclusive SRE / Discussing Platform Engineering and Inclusive SRE from an EM's Perspective
shin1988
4
5.5k
Oracle Exadata Database Service on Cloud@Customer X11M (ExaDB-C@C) サービス概要
oracle4engineer
PRO
2
8.4k
ZOZOTOWNの進化と信頼性を両立する負荷試験
zozotech
PRO
2
170
誤解だらけの開発生産性 / Myths and Misconceptions about Developer Productivity
i35_267
2
610
Featured
See All Featured
Writing Fast Ruby
sferik
630
63k
I Don’t Have Time: Getting Over the Fear to Launch Your Podcast
jcasabona
34
2.8k
The Art of Delivering Value - GDevCon NA Keynote
reverentgeek
16
2k
Designing for humans not robots
tammielis
254
26k
Visualizing Your Data: Incorporating Mongo into Loggly Infrastructure
mongodb
49
10k
Applied NLP in the Age of Generative AI
inesmontani
PRO
4
2.4k
Thoughts on Productivity
jonyablonski
76
5.2k
Java REST API Framework Comparison - PWX 2021
mraible
34
9.5k
The MySQL Ecosystem @ GitHub 2015
samlambert
251
13k
Test your architecture with Archunit
thirion
1
2.3k
svc-hook: hooking system calls on ARM64 by binary rewriting
retrage
2
330
Understanding Cognitive Biases in Performance Measurement
bluesmoon
32
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