为 Ember 计算的 属性 依赖键使用常量
Use constant for Ember computed property dependent key
对于 Ember 应用程序,是否可以使用常量作为计算的 属性 密钥的一部分?
所以,基本上,我有一个常数如下;
MY_SECTION {
MY_FIELD: "my-field-id"
}
我想要的是 "my-field-id" 上的计算 属性 即
myCP: function() {
console.log('Inside CP...');
}.property('section.field.my-field-id.value')
但是,我希望能够对 my-field-id 使用常量,而不是直接使用它。这可能吗?
Ola @testndtv,感谢您的提问!是的,完全可以在计算的 属性 的键中使用常量,但要使用它,您需要使用 @jelhan 提到的更现代的语法,因为 .poperty()
已被弃用。
这是一个控制器的工作示例,我已经在本地进行了测试,并且工作正常:
import Controller from '@ember/controller';
import { defineProperty, computed } from '@ember/object';
const PROPERTY_ID = 'some-random-string-that-is-too-long-to-write';
export default Controller.extend({
// this is just for the example so we can show the value in the template
// it is not needed to get this to work
PROPERTY_ID: PROPERTY_ID,
init() {
this._super(...arguments);
defineProperty(this, 'myCP', computed(PROPERTY_ID, function() {
return this.get(PROPERTY_ID);
}));
},
actions: {
addOne() {
// this is just for the example to stop the result always being NaN because
// null + 1 = NaN
let value = this.get(PROPERTY_ID) || 0;
this.set(PROPERTY_ID, value + 1);
}
}
});
如您所见,我们正在使用从“@ember/object”导入的 defineProperty
。您可以在 API documentation
中阅读更多相关信息
这里的关键见解是您需要在 init()
中为此 Ember 对象动态定义 属性。
这个Controller对应的模板如下:
Property ID is: {{PROPERTY_ID}}
<br>
And the value is: {{get this PROPERTY_ID}}
<br>
<button {{action 'addOne'}}>Add One</button>
对于 Ember 应用程序,是否可以使用常量作为计算的 属性 密钥的一部分?
所以,基本上,我有一个常数如下;
MY_SECTION {
MY_FIELD: "my-field-id"
}
我想要的是 "my-field-id" 上的计算 属性 即
myCP: function() {
console.log('Inside CP...');
}.property('section.field.my-field-id.value')
但是,我希望能够对 my-field-id 使用常量,而不是直接使用它。这可能吗?
Ola @testndtv,感谢您的提问!是的,完全可以在计算的 属性 的键中使用常量,但要使用它,您需要使用 @jelhan 提到的更现代的语法,因为 .poperty()
已被弃用。
这是一个控制器的工作示例,我已经在本地进行了测试,并且工作正常:
import Controller from '@ember/controller';
import { defineProperty, computed } from '@ember/object';
const PROPERTY_ID = 'some-random-string-that-is-too-long-to-write';
export default Controller.extend({
// this is just for the example so we can show the value in the template
// it is not needed to get this to work
PROPERTY_ID: PROPERTY_ID,
init() {
this._super(...arguments);
defineProperty(this, 'myCP', computed(PROPERTY_ID, function() {
return this.get(PROPERTY_ID);
}));
},
actions: {
addOne() {
// this is just for the example to stop the result always being NaN because
// null + 1 = NaN
let value = this.get(PROPERTY_ID) || 0;
this.set(PROPERTY_ID, value + 1);
}
}
});
如您所见,我们正在使用从“@ember/object”导入的 defineProperty
。您可以在 API documentation
这里的关键见解是您需要在 init()
中为此 Ember 对象动态定义 属性。
这个Controller对应的模板如下:
Property ID is: {{PROPERTY_ID}}
<br>
And the value is: {{get this PROPERTY_ID}}
<br>
<button {{action 'addOne'}}>Add One</button>