Created
June 9, 2013 22:51
-
-
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.
This file contains 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
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