discourse/app/assets/javascripts/preload_store.js

91 lines
2.2 KiB
JavaScript
Raw Normal View History

/**
We can insert data into the PreloadStore when the document is loaded.
The data can be accessed once by a key, after which it is removed
@class PreloadStore
**/
2013-12-30 12:42:05 -05:00
window.PreloadStore = {
data: {},
/**
Store an object in the store
@method store
@param {String} key the key to store the object with
@param {String} value the object we're inserting into the store
**/
store: function(key, value) {
this.data[key] = value;
},
/**
To retrieve a key, you provide the key you want, plus a finder to load
it if the key cannot be found. Once the key is used once, it is removed
from the store.
So, for example, you can't load a preloaded topic more than once.
@method getAndRemove
@param {String} key the key to look up the object with
@param {function} finder a function to find the object with
2014-09-24 14:17:09 -04:00
@returns {Promise} a promise that will eventually be the object we want.
**/
getAndRemove: function(key, finder) {
2013-10-10 12:33:24 -04:00
if (this.data[key]) {
var promise = Em.RSVP.resolve(this.data[key]);
2013-10-10 12:33:24 -04:00
delete this.data[key];
2013-07-15 19:47:13 -04:00
return promise;
}
2013-07-15 19:47:13 -04:00
if (finder) {
2014-09-24 14:17:09 -04:00
return new Ember.RSVP.Promise(function(resolve, reject) {
2013-07-15 19:47:13 -04:00
var result = finder();
// If the finder returns a promise, we support that too
if (result && result.then) {
2013-07-15 19:47:13 -04:00
result.then(function(result) {
2014-09-24 14:17:09 -04:00
return resolve(result);
2013-07-15 19:47:13 -04:00
}, function(result) {
2014-09-24 14:17:09 -04:00
return reject(result);
2013-07-15 19:47:13 -04:00
});
} else {
2014-09-24 14:17:09 -04:00
resolve(result);
}
2013-07-15 19:47:13 -04:00
});
}
2014-09-24 14:17:09 -04:00
return Ember.RSVP.resolve(null);
},
/**
If we are sure it's preloaded, we don't have to supply a finder.
Just returns undefined if it's not in the store.
@method get
@param {String} key the key to look up the object with
@returns {Object} the object from the store
**/
"get": function(key) {
return this.data[key];
},
/**
Removes the stored value if the key exists
@method remove
@param {String} key the key to remove
**/
remove: function(key) {
if (this.data[key]) delete this.data[key];
},
/**
Resets the contents of the store. Used in testing.
**/
reset: function() {
this.data = {};
}
};