Created
July 15, 2012 12:11
-
-
Save gigablah/3116495 to your computer and use it in GitHub Desktop.
Simple jQuery deferred object manager
This file contains 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
(function($) { | |
"use strict"; | |
var dictionary = {}; | |
$.Await = (function() { | |
function create(name, options) { | |
if (!(name in dictionary)) { | |
dictionary[name] = new $.Await._dictionary(name, options); | |
} | |
return dictionary[name]; | |
} | |
function destroy(name) { | |
if (name in dictionary) { | |
delete dictionary[name]; | |
} | |
} | |
var publicFunctions = { | |
create: create, | |
destroy: destroy | |
} | |
return publicFunctions; | |
})(); | |
$.Await._dictionary = function(name, options) { | |
this.name = name; | |
this.promises = {}; | |
this.resolvers = {}; | |
this.options = $.extend({}, $.Await.defaults, options); | |
}; | |
$.Await._dictionary.prototype.get = function(key) { | |
if (!(key in this.promises)) { | |
var dfd = $.Deferred(); | |
this.resolvers[key] = dfd; | |
this.promises[key] = dfd.promise(); | |
} | |
return this.promises[key]; | |
}; | |
$.Await._dictionary.prototype.set = function(key, data) { | |
if (key in this.resolvers) { | |
if (this.resolvers[key].state() === 'pending') { | |
this.resolvers[key].resolve(data); | |
this.promises[key] = data; | |
} | |
else if (this.options.overwrite) { | |
this.promises[key] = data; | |
} | |
} | |
else { | |
this.promises[key] = data; | |
} | |
}; | |
$.Await.defaults = { | |
overwrite: false | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment