Created
October 21, 2011 13:37
-
-
Save donabrams/1303869 to your computer and use it in GitHub Desktop.
Cacheing of deferred or non-deferred objects with deferred style wait queue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| define(["jquery", "jquery.addTimeoutToDeferred"], | |
| function($, addTimeoutToDeferred) { | |
| var cache = $.cache = Class.extend({ | |
| cache: {}, | |
| ready: {}, | |
| init: function(args) { | |
| this.getput = this.putget; | |
| }, | |
| contains: function(key) { | |
| return this.ready[key] !== undefined; | |
| }, | |
| // | |
| // Returns a Promise. | |
| // If resolved, resolves with the value to get. | |
| // If a maxWait is given, rejects the promise after maxWait milliseconds. | |
| // | |
| get: function(key, maxWait) { | |
| if (this.ready[key] === undefined) { | |
| var dfd = $.Deferred(); | |
| dfd.reject(); | |
| return dfd.promise(); | |
| } else if (maxWait) { | |
| return addTimeoutToDeferred(this.ready[key].promise(), maxWait); | |
| } | |
| return this.ready[key].promise(); | |
| }, | |
| // | |
| // Puts the value in the cache | |
| // | |
| put: function(key, value) { | |
| var oldVal = this.cache[key]; | |
| this.cache[key] = value; | |
| if (this.ready[key] === undefined) { | |
| this.ready[key] = $.Deferred(); | |
| } | |
| this.ready[key].resolve(value); | |
| return oldVal; | |
| }, | |
| // | |
| // Returns the same as get(). | |
| // loader may be a value or a function->Promise that resolves the value. | |
| // maxWait is optional | |
| // Constructor also aliases this function as getput. | |
| // | |
| putget: function(key, loader, maxWait) { | |
| if (this.ready[key] === undefined) { | |
| this.ready[key] = $.Deferred(); | |
| if ($.isFunction(loader)) { | |
| var that = this; | |
| loader().done(function(value) { | |
| that.put(key, value); | |
| }); | |
| } else { | |
| this.put(key, loader); | |
| } | |
| } | |
| return this.get(key, maxWait); | |
| } | |
| }); | |
| return cache; | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment