Last active
January 3, 2016 02:29
-
-
Save monzou/8396107 to your computer and use it in GitHub Desktop.
Backbone.ViewModel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UserViewModel extends Backbone.ViewModel | |
computed: | |
fullName: | |
observe: [ "firstName", "lastName" ] | |
value: -> (_.filter [ @get("firstName"), @get("lastName") ], (name) -> not _.str.isBlank name).join (" ") | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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