Last active
December 19, 2015 14:49
-
-
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.
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_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