Can I define conditional dependencies for computed properties?


#1

Suppose I have the following property:

cat: (->
  if @attack?
    @get 'dependencyA'
  else
    @get 'dependencyB'
).property('dependencyA', 'dependencyB')

If the condition @attack? is self-dependent (it is; it just checks for function existence) and resolves to true, the property will always be dependent only on dependencyA and not on dependencyB. However if dependencyB changes, the property cat will have to be computed again.

So what I want is to do the following, but perhaps in a more idiomatic way:

_init: ->
  # ... 
  descriptors = (Ember.meta @proto()).descs
  catDescriptor = descriptors['cat']
  if @attack?
    catDescriptor.willWatch 'dependencyA'
    catDescriptor.didUnwatch 'dependencyB'
  else
    catDescriptor.didUnwatch 'dependencyA'
    catDescriptor.willWatch 'dependencyB'

Edit: willWatch / didUnwatch source:

/* impl descriptor API */
ComputedPropertyPrototype.willWatch = function(obj, keyName) {
  // watch already creates meta for this instance
  var meta = obj[META_KEY];
  Ember.assert('watch should have setup meta to be writable', meta.source === obj);
  if (!(keyName in meta.cache)) {
    addDependentKeys(this, obj, keyName, meta);
  }
};

ComputedPropertyPrototype.didUnwatch = function(obj, keyName) {
  var meta = obj[META_KEY];
  Ember.assert('unwatch should have setup meta to be writable', meta.source === obj);
  if (!(keyName in meta.cache)) {
    // unwatch already creates meta for this instance
    removeDependentKeys(this, obj, keyName, meta);
  }
};