Last active
August 29, 2015 14:12
-
-
Save elegos/8034f0f4935fdb510b72 to your computer and use it in GitHub Desktop.
Allows a knockout model to be updated with fresh data composed by an object with the same structure as the viewmodel
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
ko.updateModel = (model, data, path, callback) -> | |
isObject = (obj) -> | |
typeof obj is 'object' and !Array.isArray obj | |
return if not isObject data | |
callbackIsFunction = (typeof callback) is 'function' | |
for k, v of data | |
branchPath = path + "." + k | |
if isObject(v) ## Object, recursive call | |
ko.updateModel model, v, branchPath, callback | |
else ## Data, fill the model | |
type = eval "typeof model" + branchPath | |
### There is no equivalent in the model ### | |
if type is 'undefined' | |
if callbackIsFunction | |
eval "model" + branchPath + " = callback(v, branchPath)" | |
else | |
eval "model" + branchPath + " = v" | |
## Observable if function, check | |
else if type is 'function' | |
isWritable = eval "ko.isObservable(model" + branchPath + ")" && | |
eval "ko.isWritableObservable(model" + branchPath + ")" | |
## ignore the value if is not an observable / writable | |
eval "model" + branchPath + "(v)" if isWritable | |
## Assume pure value if not a function | |
else | |
eval "model" + branchPath + " = v" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment