Skip to content

Instantly share code, notes, and snippets.

@ozeebee
Created January 14, 2014 16:31
Show Gist options
  • Save ozeebee/8421173 to your computer and use it in GitHub Desktop.
Save ozeebee/8421173 to your computer and use it in GitHub Desktop.
A generic JavaScript class that takes a plain js object and transforms it into a KnockoutJS object with support for editing (commit/reset/isDirty). Based on the work of Ryan Niemeyer : http://www.knockmeout.net/2013/01/simple-editor-pattern-knockout-js.html. Written in CoffeeScript, uses ko.mapping plugin
class EditableObj
constructor: (jsonData) ->
@hidden = -> # empty function where we will add properties that won't be exported with ko.toJS/ko.mapping.toJS
@update(jsonData)
update: (data) ->
console.log "*** update data=", data
# let ko.mapping create observable properties from the existing ones
ko.mapping.fromJS(data, {}, this)
@hidden.savedData = data
reset: ->
console.log "*** reset"
@update(@hidden.savedData)
commit: ->
console.log "*** commit"
@hidden.savedData = ko.mapping.toJS(this)
isDirty: ->
ko.mapping.toJSON(@hidden.savedData) != ko.mapping.toJSON(this)
dump: ->
console.log "EditableObj", ko.mapping.toJS(this)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment