Skip to content

Instantly share code, notes, and snippets.

@monzou
Last active January 3, 2016 02:29
Show Gist options
  • Save monzou/8396107 to your computer and use it in GitHub Desktop.
Save monzou/8396107 to your computer and use it in GitHub Desktop.
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