enlu1a
Last Updated: February 25, 2016
·
2.23K
· tjbladez
46d7c3e8ef212645ca4f942e64faef7d

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