Last Updated: May 27, 2016
·
658
· fr0gs

Access a computed property dependant on a dynamically generated key

We have to know upfront the path of the property we want to observe in order to make the expect the computed properly to fire properly. However we can define a computed property that internally creates a copy of the object with the internal variable key and accesses it extending the newly created object and adding an alias to the propery. It can be the model too but in this case it will be an object called cacheObject. The dependand variable property key name is item.id, and it will changed depending on the item we are observing in each case.

itemCacheProperty: Ember.computed , 'cacheObject', 'item.id', ->
  itemId = @get('item.id')
  if itemId
    dynamicClass = Ember.Object.extend(value: Ember.computed.alias("cacheObject.#{itemId}"))
    dynamicClass.create(cacheObject: @get('cacheObject'))
  else
    Ember.Object.create {}