Ember 引用 属性 或 getter
Ember referencing property or getter
我对何时引用 属性 以及何时使用 getter 以及原因感到有点困惑。
例如,控制器可能会为更新 location
属性:
注入服务
export default Controller.extend({
maps : service(),
location : computed('maps.location', function() {
return this.get('maps').getLocation()
}),
但是getLocation
在服务中是一个简单的getter:
getLocation() {
return this.get('location')
},
为什么不使用其中之一:
this.get('maps').location
this.get('maps').get('location')
this.get('maps.location')
并避免为每个参数编写 getters?本着约定优于配置的精神,写 getter 是不是有点多余?
简而言之,在查看示例和教程时,我看到了不同的模式:
service.property
service.get('property')
service.getProperty()
什么是正确的,什么时候以及为什么?
在线教程和论坛帖子在 Ember 目标版本中差异很大。通常甚至 2.x 分支。我现在用的是 3.8。
就像@NullVoxPopuli 提到的,这取决于您的 ember 版本,但我假设您使用的是 > 3
或最新版本。
我的第一个注意事项是,我几乎完全转向导入和使用 the get
function, which, as defined by the documentation and described very well by ,让你不知道你是否试图在普通 属性 上获得 属性 =33=] 对象或 Ember.Object
。
为了更直接地回答,我不确定您所指的服务试图完成什么,但根据您发布的内容,您很可能只需在您的内部调用 get(this, 'maps.location')
控制器,然后删除或忽略该服务方法。
Ember 文档还指出,只要您知道要从注入服务中使用的方法,就可以在当前 Ember.Object 中调用它,而无需使用 get
;像这样:
export default Controller.extend({
maps: service(),
location: computed('maps.location', function() {
return this.maps.getLocation()
})...
您可能想要使用 get
的原因是,如果您不确定 属性 您的访问是否经过计算。
When you call get
on a computed property, the function will be called and the return value will be returned instead of the function itself.
我对何时引用 属性 以及何时使用 getter 以及原因感到有点困惑。
例如,控制器可能会为更新 location
属性:
export default Controller.extend({
maps : service(),
location : computed('maps.location', function() {
return this.get('maps').getLocation()
}),
但是getLocation
在服务中是一个简单的getter:
getLocation() {
return this.get('location')
},
为什么不使用其中之一:
this.get('maps').location
this.get('maps').get('location')
this.get('maps.location')
并避免为每个参数编写 getters?本着约定优于配置的精神,写 getter 是不是有点多余?
简而言之,在查看示例和教程时,我看到了不同的模式:
service.property
service.get('property')
service.getProperty()
什么是正确的,什么时候以及为什么?
在线教程和论坛帖子在 Ember 目标版本中差异很大。通常甚至 2.x 分支。我现在用的是 3.8。
就像@NullVoxPopuli 提到的,这取决于您的 ember 版本,但我假设您使用的是 > 3
或最新版本。
我的第一个注意事项是,我几乎完全转向导入和使用 the get
function, which, as defined by the documentation and described very well by Ember.Object
。
为了更直接地回答,我不确定您所指的服务试图完成什么,但根据您发布的内容,您很可能只需在您的内部调用 get(this, 'maps.location')
控制器,然后删除或忽略该服务方法。
Ember 文档还指出,只要您知道要从注入服务中使用的方法,就可以在当前 Ember.Object 中调用它,而无需使用 get
;像这样:
export default Controller.extend({
maps: service(),
location: computed('maps.location', function() {
return this.maps.getLocation()
})...
您可能想要使用 get
的原因是,如果您不确定 属性 您的访问是否经过计算。
When you call
get
on a computed property, the function will be called and the return value will be returned instead of the function itself.