Skip to content

Instantly share code, notes, and snippets.

@ticking-clock
Created June 9, 2013 23:05
Show Gist options
  • Save ticking-clock/5745639 to your computer and use it in GitHub Desktop.
Save ticking-clock/5745639 to your computer and use it in GitHub Desktop.
Backbone.Model extension that calculates dependent attributes (computed properties)
class ComputedAttributesModel extends Backbone.Model
initialize: ->
super
return if _.isUndefined(@computed)
for attr, dependencies of @computed
@bind "change:#{attr}", =>
param = {}
param["_#{attr}"] = @[attr].call @
@set(param)
_(dependencies).each (dependencyAttr) =>
@bind "change:#{dependencyAttr}", =>
@trigger "change:#{attr}"
@trigger "change:#{attr}" if @has(dependencyAttr)
get: (attr) ->
attr = "_#{attr}" if @computed?.hasOwnProperty(attr)
super attr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment