Skip to content

Instantly share code, notes, and snippets.

@tjbladez
Created May 8, 2012 17:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tjbladez/2637522 to your computer and use it in GitHub Desktop.
Save tjbladez/2637522 to your computer and use it in GitHub Desktop.
basic computed properties in backbone
Namespace.models.Base = Backbone.Model.extend
initialize: ()->
Backbone.Model::initialize @, arguments
return if _.isUndefined(@computed)
@_computed = {}
for attr, dependencies of @computed
@on "change:#{attr}", ()=>
@_computed[attr] = @[attr].call @
_(dependencies).each (dep)=>
@on "change:#{dep}", ()=>
@trigger "change:#{attr}"
@trigger "change:#{attr}" if @has(dep)
get: (attr)->
if @computed?.hasOwnProperty(attr)
@_computed[attr]
else
Backbone.Model::get.call @, attr
Namespace.models.Example = Namespace.models.Base.extend
computed:
fullName: ['firstName', 'lastName']
fullName: ()->
"#{@get('firstName')} #{@get('lastName')}"
@tjbladez
Copy link
Author

tjbladez commented May 9, 2012

Cool, thanks

@curran
Copy link

curran commented Mar 24, 2014

Greetings,

Here is a small function that implements computed properties for Backbone https://github.com/curran/backboneComputedProperties .

Regards,
Curran

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment