Created
December 14, 2013 18:18
-
-
Save nathggns/7962799 to your computer and use it in GitHub Desktop.
A type to represent observables where the value of it is in a promise ($.Deferred, Q, etc).
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
/** | |
* Just a type to store deferred observables. | |
* | |
* When the deferred is resolved, it'll set the value of the observable | |
* to result of the deferred. | |
* | |
* @param {Function} observable The function to use for the | |
* observable | |
* @param {$.Deferred} deferred The deferred value | |
* @param {Boolean} shouldSetObsValue Should we set the value of the | |
* observable? | |
*/ | |
var DeferredObservable = function(observable, deferred, shouldSetObsValue) { | |
/** | |
* Check to make sure we've iniated via the new pattern. | |
*/ | |
if (!(this instanceof DeferredObservable)) { | |
return new DeferredObservable( | |
observable, deferred, shouldSetObsValue | |
); | |
} | |
if (typeof shouldSetObsValue === 'undefined') { | |
shouldSetObsValue = true; | |
} | |
/** | |
* Get a new deferred that resolves with the observable, | |
* and sets the observables value | |
*/ | |
var newDeferred = deferred.then(function(value) { | |
if (shouldSetObsValue) { | |
observable(value); | |
} | |
return observable; | |
}); | |
/** | |
* Just set some properties | |
*/ | |
this.observable = observable; | |
this.deferred = newDeferred.promise(); | |
}; |
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
var ko = require('knockout'); | |
var DeferredObservable = require('DeferredObservable'); | |
var tasks = ko.observableArray([]); | |
var ajax = util.getTasks(); // Or whatever | |
var deferredObs = new DeferredObservable(tasks, ajax); | |
// tasks will automatically be filled will the result of the ajax call. | |
// deferredObs has a property, "deferred", that is a promise representing the | |
// observable too, and will only be resolved when the request is done. | |
// This seems useless, but it actually helps a lot in SPA-like applications. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment