Skip to content

Instantly share code, notes, and snippets.

@monzou monzou/
Last active Jan 3, 2016

What would you like to do?
class UserViewModel extends Backbone.ViewModel
observe: [ "firstName", "lastName" ]
value: -> (_.filter [ @get("firstName"), @get("lastName") ], (name) -> not _.str.isBlank name).join (" ")
class Backbone.ViewModel extends Backbone.Model
constructor: (attributes={}, options={}) ->
super attributes, options
@initializeViewModel options
initializeViewModel: (options) ->
@handlers = {}
@initializeModel options.model if options.model
initializeModel: (model) ->
@model = model
@set Backbone.$.extend true, {}, @model.toJSON()
bindAttributeChangeHandlers: ->
_.each @computed, (handler, key) =>
events = undefined
events = ( handler.observe, (attr) -> "change:#{attr}").join(" ") if handler.observe
value = _.bind handler.value, @
fn = => @set key, @
@on events, fn, @ if events
@handlers[key] = event: events, fn: fn
unbindAttributeChangeHandlers: ->
for key, handler of @handlers
@off handler.event, handler.fn if handler.event
delete @handlers[key]
commit: ->
@model.set _.omit(@toJSON(), (_.keys @handlers)) if @model
@model or @
sync: ->
throw "Unsupported operation"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.