Last Updated: February 25, 2016
·
2.648K
· tjbladez

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')}"