Skip to content

Instantly share code, notes, and snippets.

@joeflateau
Created December 16, 2013 16:17
Show Gist options
  • Save joeflateau/7989689 to your computer and use it in GitHub Desktop.
Save joeflateau/7989689 to your computer and use it in GitHub Desktop.
Super easy jQuery+KnockoutJS deferred observable w/ajax
function deferredObservable(initialValue, creator){
if (!creator){
creator = initialValue;
initialValue = null;
}
if ($.type(creator) === "string") {
var getUrl = creator;
creator = function(){ return $.get(getUrl); };
}
var observable = ko.observable(initialValue);
ko.computed(function(){
creator()
.done(function(val){
observable(val);
});
});
return observable;
}
// simple GET request
// var observable = deferredObservable("/service/getData");
// initialize the observable
// var observable = deferredObservable([], "/service/getData");
// a function that returns a deferred, any time dependencies change, a new GET will be made
// var observable = deferredObservable([], function(){ $.get("/service/getData", ko.toJS(otherObservables)); });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment