Created
October 22, 2010 12:48
-
-
Save sagacity/640485 to your computer and use it in GitHub Desktop.
Creates a knockout viewmodel from a regular object
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
/* | |
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