在模型挂钩后设置控制器属性 [英] Setting up a controller property after the model hook
问题描述
我需要在模型
钩子之后设置一个控制器属性。我可以想到两种方法:
I need to set a controller property after the model
hook. I can think of two ways to do this:
model(params) {
return this.store.findRecord('user', 1);
},
afterModel(model, transition) {
model.get('profile').then(profile => {
this.set('profile', profile);
});
},
setupController(controller, model) {
controller.set('model', model);
controller.set('profile', this.get('profile'));
},
另一种方法。即跳过 setupController
:
model(params) {
return this.store.findRecord('user', 1);
},
afterModel(model, transition) {
model.get('profile').then(profile => {
this.controller.set('profile', profile);
});
},
两者似乎都工作。
任何一种方法都有附加的优点/缺点?显然,后者较短。但是在code后面的控制器属性中设置控件属性是否感觉干净吗?
Are there any added advantages / disadvantages with either approach? Clearly, the latter is shorter. But does it feel "clean" to set the controller property in an afterModel
hook?
编辑: user
和个人资料
之间的关系/关联是 async
。
EDIT: the relationship/association between user
and profile
is async
.
推荐答案
另外一个海报指出,你可以访问 model.profile
,但是如果个人资料
是一个异步关联,则代码将无法工作:
As another poster pointed out, you can access model.profile
, but that won't work from code if profile
is an async association:
// models/user.js
profile: belongsTo('profile', { async: true })
原因是 model.profile
将返回承诺而不是值。为了解决这个问题,你可以按照你的建议,使用 afterModel
钩,但你需要的只是
The reason is that model.profile
will return a promise rather than a value. To solve that, you can use the afterModel
hook as you suggested, but all you need is
afterModel(model, transition) {
return model.get('profile');
},
这将发出异步调用并暂停转换,直到完成,在这一点上,个人资料
可以像往常一样以 model.profile
方式访问。如果由于某种原因,您真的想要将该配置文件作为控制器属性访问,以避免使用模型前缀。
,只需在控制器中定义别名:
That will issue the async call and pause the transition until it is completed, at which point the profile
may be accessed as model.profile
as usual. If for some reason you really want to access the profile as a controller property to avoid having to prefix it with model.
, just define an alias in your controller:
profile: Ember.computed.alias('model.profile')
如果有不止一个这样的财产,那么以下工作应该执行:
If there is more than one such property, then the following should do the job:
return Ember.RSVP.Promise.hash(this.getProperties('profile', ...));
您还可以在模型中实现此权限
钩子,虽然它有点不太可读:
You could also implement this right in the model
hook, although it's a bit less readable:
model() {
return this.store.findRecord('user', 1) .
then(user => user.get('profile') .
then(() => user)
);
}
这是什么,找到用户,然后找到他的个人资料(这将导致异步请求触发),那么当发现该命令返回用户从承诺,所以它被正确设置为模型
。
What this says is, find the user, and then when found get his profile (which will cause the async request to fire), then when that is found return the user from the promise, so it is correctly set into model
.
这篇关于在模型挂钩后设置控制器属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!