Created
December 16, 2013 16:17
-
-
Save joeflateau/7989689 to your computer and use it in GitHub Desktop.
Super easy jQuery+KnockoutJS deferred observable w/ajax
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 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