SlideShare a Scribd company logo
BUILDING SMART ASYNC
FUNCTIONS FOR MOBILE
              Glan Thomas
   Mountain View JavaScript Meetup Group
               Aug 10, 2011
TYPICAL ASYNC FUNCTIONS
getJSON(url, [data,] [success(data, textStatus, jqXHR),] [dataType])

get(url, [data,] [success(data, textStatus, jqXHR),] [dataType])

post(url, [data,] [success(data, textStatus, jqXHR),] [dataType])
ASYNC PROBLEMS

• Requires   an HTTP request

• Requires   a network connection

• Cross   domain origin
OBJECTIVES

• Minimize   HTTP requests

• Make    things work even if you are offline

• Avoid cluttering up the app’s controllers with online/offline
 conditionals

• Preserve   original API signatures
  getJSON( url, [data,] [success,] [cache,] [filter,] [keyboardcat] )
WHAT CAN WE DO?

• Cache    - Keep a local copy of the data

• Queue     - For sending to the server later

• Merge    - Combine requests into one

• Filter   - Transform the incoming data

• AB   Testing - Provide different data for different users

• Versioning     - Making sure you hit the right endpoints
TECHNIQUES

• Interfaces   - for utility objects

• Decorators    - for augmenting async functions

• Delegation    - to utility object
INTERFACES

Cache Interface        Queue Interface

 • get(key)             • add(item)

 • set(key,   value)    • remove()

 • delete(key)
DECORATORS
WHAT JUST HAPPENED?




jQuery.get   CacheDecorator   getCached
USAGE

var cache = new Cache(),

myGet = jQuery.get;

myGet = new CacheDecorator(myGet, cache);

myGet(url, successFunction);
CACHE DECORATOR
var CacheDecorator = function (func, cache) {
    'use strict';
    return function (url, success) {
        var data = cache.get(url);
        if (data) {
            success(data, 'hit');
        } else {
            func(url, function (data) {
                 cache.set(url, data);
                 if (typeof success === 'function') {
                     success.apply(this, arguments);
                 }
            });
        }
    };
};
STACKING

var cache = new Cache(), filter = new Filter(),

myGet = jQuery.get;

myGet = new FilterDecorator(myGet, filter);

myGet = new CacheDecorator(myGet, cache);

myGet(url, successFunction);
FILTER DECORATOR
var FilterDecorator = function (func, filter) {
    'use strict';
    return function (url, success) {
        func(url, function (data) {
            data = filter(url, data);
            if (typeof success === 'function') {
                success.apply(this, arguments);
            }
        });
    };
};
QUEUE DECORATOR
var QueueDecorator = function (func, queue) {
    'use strict';
    return function (url, data, success) {
        queue.add({'func': func, 'args' : arguments});
        success({}, 'queued');
    };
};
TAKEAWAYS

• Usedecorators to enhance existing asynchronous functions
 without altering their signatures.

• Delegate
         functionality to dedicated utility objects (Caching/
 Queuing).

• Define    interfaces for utility objects.

• Stack   decorators to combine functionality.
SOME THINGS WE SKIPPED

• Cross   domain origin

• Error   and failure states

• Specificimplementations of Cache and Queue classes
 (LocalStorage/SQLite)

• Enforcing   of interfaces
 (see ‘Pro JavaScript Design Patterns’, Ross Harmes and Dustin Diaz, Apress, 2008)
QUESTIONS?
CACHE IMPLEMENTATION
Cache.prototype = {
    set : function (key, value) {
        var package = {};
        package.type = typeof value;
        package.value = (package.type === 'object') ? JSON.stringify(value) : value;
        localStorage[this._hash(key)] = JSON.stringify(package);
    },
    get : function (key) {
        var package;
        if (this._exists(key)) {
            try {
                package = JSON.parse(localStorage[this._hash(key)]);
            } catch (e) {
                this.remove(key);
                return false;
            }
            return (package.type === 'object') ? JSON.parse(package.value) : package.value;
        }
        return false;
    },
    remove : function (key) {
        if (this._exists(key)) {
            delete localStorage[this._hash(key)];
        }
    }
}
QUEUE IMPLEMENTATION
var Queue = function() {};
Queue.prototype = new Array();

Queue.prototype.add = function (item) {
   this.push(item);
};
Queue.prototype.remove = function () {
    return this.shift();
};
Queue.prototype.goOnline = function () {
    var self = this, success;
    if(item = this[0]) {
       success = item.args[2];
       item.args[2] = function () {
          success.apply(this, arguments);
          self.remove();
          self.goOnline();
       };
       item.func.apply(this, item.args);
    }
};

var queue = new Queue();

document.body.addEventListener("online", function () {
   queue.goOnline();
}, false);
OFFLINE DECORATOR
var OfflineDecorator = function (func, offLine) {
    'use strict';
    return function (url, success) {
        if (offLine) {
            success({}, 'offline');
        } else {
            func(url, function (data) {
                 if (typeof success === 'function') {
                     success.apply(this, arguments);
                 }
            });
        }
    };
};

More Related Content

What's hot (20)

Tweaking the interactive grid
Tweaking the interactive gridTweaking the interactive grid
Tweaking the interactive grid
Roel Hartman
 
"Inside The AngularJS Directive Compiler" by Tero Parviainen
"Inside The AngularJS Directive Compiler" by Tero Parviainen"Inside The AngularJS Directive Compiler" by Tero Parviainen
"Inside The AngularJS Directive Compiler" by Tero Parviainen
Fwdays
 
ReactでGraphQLを使っている
ReactでGraphQLを使っているReactでGraphQLを使っている
ReactでGraphQLを使っている
Takahiro Kobaru
 
React lecture
React lectureReact lecture
React lecture
Christoffer Noring
 
Angular mix chrisnoring
Angular mix chrisnoringAngular mix chrisnoring
Angular mix chrisnoring
Christoffer Noring
 
Rxjs vienna
Rxjs viennaRxjs vienna
Rxjs vienna
Christoffer Noring
 
PGConf APAC 2018 - Lightening Talk #2 - Centralizing Authorization in PostgreSQL
PGConf APAC 2018 - Lightening Talk #2 - Centralizing Authorization in PostgreSQLPGConf APAC 2018 - Lightening Talk #2 - Centralizing Authorization in PostgreSQL
PGConf APAC 2018 - Lightening Talk #2 - Centralizing Authorization in PostgreSQL
PGConf APAC
 
Polyglot parallelism
Polyglot parallelismPolyglot parallelism
Polyglot parallelism
Phillip Toland
 
An introduction to property-based testing
An introduction to property-based testingAn introduction to property-based testing
An introduction to property-based testing
Vincent Pradeilles
 
Firebase ng2 zurich
Firebase ng2 zurichFirebase ng2 zurich
Firebase ng2 zurich
Christoffer Noring
 
PerlApp2Postgresql (2)
PerlApp2Postgresql (2)PerlApp2Postgresql (2)
PerlApp2Postgresql (2)
Jerome Eteve
 
Speed Things Up with Transients
Speed Things Up with TransientsSpeed Things Up with Transients
Speed Things Up with Transients
Cliff Seal
 
PostgreSQL Open SV 2018
PostgreSQL Open SV 2018PostgreSQL Open SV 2018
PostgreSQL Open SV 2018
artgillespie
 
My Top 5 APEX JavaScript API's
My Top 5 APEX JavaScript API'sMy Top 5 APEX JavaScript API's
My Top 5 APEX JavaScript API's
Roel Hartman
 
Owl: The New Odoo UI Framework
Owl: The New Odoo UI FrameworkOwl: The New Odoo UI Framework
Owl: The New Odoo UI Framework
Odoo
 
Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with Jasmine
Tim Tyrrell
 
Lucene
LuceneLucene
Lucene
Matt Wood
 
Clustering your Application with Hazelcast
Clustering your Application with HazelcastClustering your Application with Hazelcast
Clustering your Application with Hazelcast
Hazelcast
 
Europython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & CeleryEuropython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & Celery
Mauro Rocco
 
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseCodepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Sages
 
Tweaking the interactive grid
Tweaking the interactive gridTweaking the interactive grid
Tweaking the interactive grid
Roel Hartman
 
"Inside The AngularJS Directive Compiler" by Tero Parviainen
"Inside The AngularJS Directive Compiler" by Tero Parviainen"Inside The AngularJS Directive Compiler" by Tero Parviainen
"Inside The AngularJS Directive Compiler" by Tero Parviainen
Fwdays
 
ReactでGraphQLを使っている
ReactでGraphQLを使っているReactでGraphQLを使っている
ReactでGraphQLを使っている
Takahiro Kobaru
 
PGConf APAC 2018 - Lightening Talk #2 - Centralizing Authorization in PostgreSQL
PGConf APAC 2018 - Lightening Talk #2 - Centralizing Authorization in PostgreSQLPGConf APAC 2018 - Lightening Talk #2 - Centralizing Authorization in PostgreSQL
PGConf APAC 2018 - Lightening Talk #2 - Centralizing Authorization in PostgreSQL
PGConf APAC
 
An introduction to property-based testing
An introduction to property-based testingAn introduction to property-based testing
An introduction to property-based testing
Vincent Pradeilles
 
PerlApp2Postgresql (2)
PerlApp2Postgresql (2)PerlApp2Postgresql (2)
PerlApp2Postgresql (2)
Jerome Eteve
 
Speed Things Up with Transients
Speed Things Up with TransientsSpeed Things Up with Transients
Speed Things Up with Transients
Cliff Seal
 
PostgreSQL Open SV 2018
PostgreSQL Open SV 2018PostgreSQL Open SV 2018
PostgreSQL Open SV 2018
artgillespie
 
My Top 5 APEX JavaScript API's
My Top 5 APEX JavaScript API'sMy Top 5 APEX JavaScript API's
My Top 5 APEX JavaScript API's
Roel Hartman
 
Owl: The New Odoo UI Framework
Owl: The New Odoo UI FrameworkOwl: The New Odoo UI Framework
Owl: The New Odoo UI Framework
Odoo
 
Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with Jasmine
Tim Tyrrell
 
Clustering your Application with Hazelcast
Clustering your Application with HazelcastClustering your Application with Hazelcast
Clustering your Application with Hazelcast
Hazelcast
 
Europython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & CeleryEuropython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & Celery
Mauro Rocco
 
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseCodepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Sages
 

Similar to Building Smart Async Functions For Mobile (20)

Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
Jarod Ferguson
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
Nick Lee
 
Backbone.js Simple Tutorial
Backbone.js Simple TutorialBackbone.js Simple Tutorial
Backbone.js Simple Tutorial
추근 문
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
Guy Royse
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
Ankit Rastogi
 
Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
Ryunosuke SATO
 
AngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesAngularJS - $http & $resource Services
AngularJS - $http & $resource Services
Eyal Vardi
 
Migrating from Flux to Redux. Why and how.
Migrating from Flux to Redux. Why and how.Migrating from Flux to Redux. Why and how.
Migrating from Flux to Redux. Why and how.
Astrails
 
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web Module
Morgan Cheng
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
Adam Crabtree
 
Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3
Simon Su
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
Sunghyouk Bae
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
Nishan Subedi
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScript
Ryan Anklam
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
Bret Little
 
AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS Services
Eyal Vardi
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
Chris Neale
 
Bindings: the zen of montage
Bindings: the zen of montageBindings: the zen of montage
Bindings: the zen of montage
Kris Kowal
 
Redux vs Alt
Redux vs AltRedux vs Alt
Redux vs Alt
Uldis Sturms
 
Akka Cluster in Java - JCConf 2015
Akka Cluster in Java - JCConf 2015Akka Cluster in Java - JCConf 2015
Akka Cluster in Java - JCConf 2015
Jiayun Zhou
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
Jarod Ferguson
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
Nick Lee
 
Backbone.js Simple Tutorial
Backbone.js Simple TutorialBackbone.js Simple Tutorial
Backbone.js Simple Tutorial
추근 문
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
Guy Royse
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
Ankit Rastogi
 
AngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesAngularJS - $http & $resource Services
AngularJS - $http & $resource Services
Eyal Vardi
 
Migrating from Flux to Redux. Why and how.
Migrating from Flux to Redux. Why and how.Migrating from Flux to Redux. Why and how.
Migrating from Flux to Redux. Why and how.
Astrails
 
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web Module
Morgan Cheng
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
Adam Crabtree
 
Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3
Simon Su
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
Nishan Subedi
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScript
Ryan Anklam
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
Bret Little
 
AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS Services
Eyal Vardi
 
Bindings: the zen of montage
Bindings: the zen of montageBindings: the zen of montage
Bindings: the zen of montage
Kris Kowal
 
Akka Cluster in Java - JCConf 2015
Akka Cluster in Java - JCConf 2015Akka Cluster in Java - JCConf 2015
Akka Cluster in Java - JCConf 2015
Jiayun Zhou
 

Recently uploaded (20)

Web and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in RajpuraWeb and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in Rajpura
Erginous Technology
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Vaibhav Gupta BAML: AI work flows without Hallucinations
Vaibhav Gupta BAML: AI work flows without HallucinationsVaibhav Gupta BAML: AI work flows without Hallucinations
Vaibhav Gupta BAML: AI work flows without Hallucinations
john409870
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Top 10 IT Help Desk Outsourcing Services
Top 10 IT Help Desk Outsourcing ServicesTop 10 IT Help Desk Outsourcing Services
Top 10 IT Help Desk Outsourcing Services
Infrassist Technologies Pvt. Ltd.
 
Web and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in RajpuraWeb and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in Rajpura
Erginous Technology
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Vaibhav Gupta BAML: AI work flows without Hallucinations
Vaibhav Gupta BAML: AI work flows without HallucinationsVaibhav Gupta BAML: AI work flows without Hallucinations
Vaibhav Gupta BAML: AI work flows without Hallucinations
john409870
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 

Building Smart Async Functions For Mobile

  • 1. BUILDING SMART ASYNC FUNCTIONS FOR MOBILE Glan Thomas Mountain View JavaScript Meetup Group Aug 10, 2011
  • 2. TYPICAL ASYNC FUNCTIONS getJSON(url, [data,] [success(data, textStatus, jqXHR),] [dataType]) get(url, [data,] [success(data, textStatus, jqXHR),] [dataType]) post(url, [data,] [success(data, textStatus, jqXHR),] [dataType])
  • 3. ASYNC PROBLEMS • Requires an HTTP request • Requires a network connection • Cross domain origin
  • 4. OBJECTIVES • Minimize HTTP requests • Make things work even if you are offline • Avoid cluttering up the app’s controllers with online/offline conditionals • Preserve original API signatures getJSON( url, [data,] [success,] [cache,] [filter,] [keyboardcat] )
  • 5. WHAT CAN WE DO? • Cache - Keep a local copy of the data • Queue - For sending to the server later • Merge - Combine requests into one • Filter - Transform the incoming data • AB Testing - Provide different data for different users • Versioning - Making sure you hit the right endpoints
  • 6. TECHNIQUES • Interfaces - for utility objects • Decorators - for augmenting async functions • Delegation - to utility object
  • 7. INTERFACES Cache Interface Queue Interface • get(key) • add(item) • set(key, value) • remove() • delete(key)
  • 9. WHAT JUST HAPPENED? jQuery.get CacheDecorator getCached
  • 10. USAGE var cache = new Cache(), myGet = jQuery.get; myGet = new CacheDecorator(myGet, cache); myGet(url, successFunction);
  • 11. CACHE DECORATOR var CacheDecorator = function (func, cache) { 'use strict'; return function (url, success) { var data = cache.get(url); if (data) { success(data, 'hit'); } else { func(url, function (data) { cache.set(url, data); if (typeof success === 'function') { success.apply(this, arguments); } }); } }; };
  • 12. STACKING var cache = new Cache(), filter = new Filter(), myGet = jQuery.get; myGet = new FilterDecorator(myGet, filter); myGet = new CacheDecorator(myGet, cache); myGet(url, successFunction);
  • 13. FILTER DECORATOR var FilterDecorator = function (func, filter) { 'use strict'; return function (url, success) { func(url, function (data) { data = filter(url, data); if (typeof success === 'function') { success.apply(this, arguments); } }); }; };
  • 14. QUEUE DECORATOR var QueueDecorator = function (func, queue) { 'use strict'; return function (url, data, success) { queue.add({'func': func, 'args' : arguments}); success({}, 'queued'); }; };
  • 15. TAKEAWAYS • Usedecorators to enhance existing asynchronous functions without altering their signatures. • Delegate functionality to dedicated utility objects (Caching/ Queuing). • Define interfaces for utility objects. • Stack decorators to combine functionality.
  • 16. SOME THINGS WE SKIPPED • Cross domain origin • Error and failure states • Specificimplementations of Cache and Queue classes (LocalStorage/SQLite) • Enforcing of interfaces (see ‘Pro JavaScript Design Patterns’, Ross Harmes and Dustin Diaz, Apress, 2008)
  • 18. CACHE IMPLEMENTATION Cache.prototype = { set : function (key, value) { var package = {}; package.type = typeof value; package.value = (package.type === 'object') ? JSON.stringify(value) : value; localStorage[this._hash(key)] = JSON.stringify(package); }, get : function (key) { var package; if (this._exists(key)) { try { package = JSON.parse(localStorage[this._hash(key)]); } catch (e) { this.remove(key); return false; } return (package.type === 'object') ? JSON.parse(package.value) : package.value; } return false; }, remove : function (key) { if (this._exists(key)) { delete localStorage[this._hash(key)]; } } }
  • 19. QUEUE IMPLEMENTATION var Queue = function() {}; Queue.prototype = new Array(); Queue.prototype.add = function (item) { this.push(item); }; Queue.prototype.remove = function () { return this.shift(); }; Queue.prototype.goOnline = function () { var self = this, success; if(item = this[0]) { success = item.args[2]; item.args[2] = function () { success.apply(this, arguments); self.remove(); self.goOnline(); }; item.func.apply(this, item.args); } }; var queue = new Queue(); document.body.addEventListener("online", function () { queue.goOnline(); }, false);
  • 20. OFFLINE DECORATOR var OfflineDecorator = function (func, offLine) { 'use strict'; return function (url, success) { if (offLine) { success({}, 'offline'); } else { func(url, function (data) { if (typeof success === 'function') { success.apply(this, arguments); } }); } }; };