Ember.computed在方法中定义时不能按预期运行

时间:2013-03-14 04:04:40

标签: ember.js

我试图使用Ember.computed从我的一个视图方法中设置一个计算属性。我试图使用这个小提琴中显示的语法,但正如你所看到的,它似乎并没有真正做我希望的。任何指向正确方向的人都会非常感激。

http://jsfiddle.net/skane/H5ma5/1/

this.set('myComputed', Ember.computed(function() {return "funky"}).property());

史蒂夫

1 个答案:

答案 0 :(得分:5)

这不会这样,因为Ember必须执行一些魔术。我看了一下Ember的来源,发现了this

// define a computed property
  Ember.defineProperty(contact, 'fullName', Ember.computed(function() {
    return this.firstName+' '+this.lastName;
  }).property('firstName', 'lastName'));

  @method defineProperty
  @for Ember
  @param {Object} obj the object to define this property on. This may be a prototype.
  @param {String} keyName the name of the property
  @param {Ember.Descriptor} [desc] an instance of `Ember.Descriptor` (typically a
    computed property) or an ES5 descriptor.
    You must provide this or `data` but not both.
  @param {anything} [data] something other than a descriptor, that will
    become the explicit value of this property.

因此,以下情况适用于您的情况:

Ember.defineProperty(this, 'myComputed', Ember.computed(function() {
    return "funky";
}).property());