Skip to content

Instantly share code, notes, and snippets.

@elegos
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elegos/8034f0f4935fdb510b72 to your computer and use it in GitHub Desktop.
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
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