我试图定义一个依赖于一组属性的计算属性,这些属性被指定为一个数组。 这个小提琴给出了一个例子:
var MyObject = Ember.Object.extend({ properties: ['red', 'blue'], red: 'i am red', blue: 'blue am i', defineMagic: function () { var thiz = this; Ember.defineProperty(thiz, 'magic', Ember.computed(function () { console.log('i am called'); return thiz.getProperties(thiz.get('properties')); }).property(thiz.get('properties').toString()/*what goes here */)); } });到目前为止,我已经使用Ember的defineProperty方法来定义计算属性。 但是,如果基础属性发生变化,计算属性不会重新计算,如小提琴中的注释中所述。 一定要激活控制台,因为我试图验证控制台输出。
这在Ember中是否可行,如果可以的话; 如何使用它?
I am trying to define a computed property that depends upon a set of properties, which are specified as an array. The example is given in this fiddle:
var MyObject = Ember.Object.extend({ properties: ['red', 'blue'], red: 'i am red', blue: 'blue am i', defineMagic: function () { var thiz = this; Ember.defineProperty(thiz, 'magic', Ember.computed(function () { console.log('i am called'); return thiz.getProperties(thiz.get('properties')); }).property(thiz.get('properties').toString()/*what goes here */)); } });So far, I have used Ember's defineProperty method to define a computed property. But the computed property does not get recomputed if the underlying properties change, as noted in the comments in the fiddle. Be sure to activate console, as I am trying to validate against the console output.
Is this possible at all in Ember, and if so; how to use it?
最满意答案
你可以通过Function#apply的魔力来做到这一点。 apply通过将传递的数组转换为参数列表来调用函数。 (另一方面, Function#call #call采用正常的逗号分隔的参数列表)。 尝试这个:
var func = function () { return this.get('properties'); }; var args = this.get('properties').concat([func]); Ember.defineProperty(this, 'magic', Ember.computed.apply(this, args));这相当于
Ember.defineProperty(this, 'magic', Ember.computed('red', 'blue', func));另外:在计算属性中, this指的是它是属性的对象,因此您不希望引用that / thiz等来获取该对象。
You can do this with the magic of Function#apply. apply calls a function by translating the passed array into an arguments list. (Function#call, on the other hand, takes a normal comma separated list of arguments). Try this:
var func = function () { return this.get('properties'); }; var args = this.get('properties').concat([func]); Ember.defineProperty(this, 'magic', Ember.computed.apply(this, args));This is equivalent to
Ember.defineProperty(this, 'magic', Ember.computed('red', 'blue', func));Also: in a computed property this refers to the object of which it is a property, so you don't want to be referencing that/thiz etc to get to the object.
更多推荐
发布评论