Skip to content

Instantly share code, notes, and snippets.

@monzou monzou/user.coffee
Last active Jan 3, 2016

Embed
What would you like to do?
Backbone.ViewModel
class UserViewModel extends Backbone.ViewModel
computed:
fullName:
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
@bindAttributeChangeHandlers()
initializeModel: (model) ->
@model = model
@set Backbone.$.extend true, {}, @model.toJSON()
bindAttributeChangeHandlers: ->
_.each @computed, (handler, key) =>
events = undefined
events = (_.map handler.observe, (attr) -> "change:#{attr}").join(" ") if handler.observe
value = _.bind handler.value, @
fn = => @set key, value.call @
fn.call()
@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.