Skip to content

Instantly share code, notes, and snippets.

@ticking-clock
Created June 9, 2013 22:51
Show Gist options
  • Save ticking-clock/5745595 to your computer and use it in GitHub Desktop.
Save ticking-clock/5745595 to your computer and use it in GitHub Desktop.
A mixin that adds computed properties to Backbone.Model. Works, but alters get() in a way that mixins should not.
Backbone.Model.mixin ||= (mixin) ->
_.extend(@prototype, mixin)
Backbone.Mixins ||= {}
Backbone.Mixins.ComputedAttributes =
initialize: ->
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)
Backbone.Model::get.call @, attr
class TestModel extends Backbone.Model
@mixin Backbone.Mixins.ComputedAttributes
defaults:
coordinates: [3, 4]
computed:
x: ["coordinates"]
y: ["coordinates"]
x: -> @get("coordinates")[0]
y: -> @get("coordinates")[1]
test = new TestModel
alert "x = #{test.get('x')}, y = #{test.get('y')}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment