Skip to content

Instantly share code, notes, and snippets.

@sagacity
Created October 22, 2010 12:48
Show Gist options
  • Save sagacity/640485 to your computer and use it in GitHub Desktop.
Save sagacity/640485 to your computer and use it in GitHub Desktop.
Creates a knockout viewmodel from a regular object
/*
Usage:
var viewModel = createFrom(regularObject);
To update the viewmodel:
viewModel.updateFrom(newRegularObject);
*/
var createFrom = function(source, destination, isNested) {
if (!destination) destination = {};
for (var prop in source) {
if (typeof source[prop] == "object") {
if (typeof destination[prop] == "undefined") {
destination[prop] = {};
}
createFrom(source[prop], destination[prop], true);
} else {
if (typeof destination[prop] == "undefined") {
destination[prop] = ko.observable(source[prop]);
} else {
destination[prop](source[prop]);
}
}
}
if (!isNested) {
if (typeof destination.updateFrom == "undefined") {
destination.updateFrom = function(source) {
createFrom(source, destination);
}
}
}
return destination;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment