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
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)