Skip to content

Instantly share code, notes, and snippets.

@evanisnor
Last active December 19, 2015 14:49
Show Gist options
  • Save evanisnor/5971578 to your computer and use it in GitHub Desktop.
Save evanisnor/5971578 to your computer and use it in GitHub Desktop.
JavaScript functions to wrap and unwrap a JSON object and its entire contents with KnockoutJS's ko.observable (and ko.observableArray). The odd nested-function layout here is a hangover from using requirejs. Cannibalize as needed.
var ko_wrapper = function(ko) {
var data = {};
data.wrap = function(obj) {
if (Object.prototype.toString.call(obj) == '[object Array]'
|| Object.prototype.toString.call(obj) == '[object Object]') {
for (var i in obj) {
obj[i] = data.wrap(obj[i]);
}
}
if (Object.prototype.toString.call(obj) == '[object Array]') {
return ko.observableArray(obj);
}
else {
return ko.observable(obj);
}
}
data.unwrap = function(obj) {
if (Object.prototype.toString.call(obj) == '[object Array]'
|| Object.prototype.toString.call(obj) == '[object Object]') {
for (var i in obj()) {
obj[i] = data.unwrap(obj()[i]);
}
}
if (typeof(value) === 'function') {
return obj();
}
else {
return obj;
}
}
return data;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment