根据属性数组定义Ember计算属性(Defining an Ember computed property based on an array of properties)

编程入门 行业动态 更新时间:2024-10-24 04:51:47
根据属性数组定义Ember计算属性(Defining an Ember computed property based on an array of properties)

我试图定义一个依赖于一组属性的计算属性,这些属性被指定为一个数组。 这个小提琴给出了一个例子:

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.

更多推荐

本文发布于:2023-07-27 17:48:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1293576.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   数组   定义   Ember   Defining

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!