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')}"
Written by Nickolay Schwarz
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Frontend frameworks
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#