[英]Set an Ember.js controller variable to an Ember Data object, not a promise
I have a route that initially has no suggestion. 我有一条最初没有任何建议的路线。 Based on an action, I would like to grab a suggestions array with Ember Data, get the first suggestion and assign it to the controller.
基于动作,我想获取一个带有Ember Data的建议数组,得到第一个建议并将其分配给控制器。 Here's what I've got:
这是我得到的:
App.IndexRoute = Ember.Route.extend({
setupController: function(controller, model) {
this._super(controller, model);
controller.set('suggestion', null);
},
actions: {
getSuggestion: function() {
suggestion = this.store.find('suggestion').then(function(s) {
return s.get('firstObject');
});
this.controller.set('suggestion', suggestion);
}
}
});
The problem is that the suggestion
variable, after performing the getSuggestion
action, it still a promise. 问题是
suggestion
变量在执行getSuggestion
操作后仍然是一个promise。 How can I only set the controller variable after the promise is resolved? 如何在解析promise之后才设置控制器变量? Or how can I let it resolve afterwards and have the variable updated with the actual object?
或者我怎样才能让它在事后解决并使用实际对象更新变量?
Set the property on resolution of the promise: 根据承诺的分辨率设置属性:
actions: {
getSuggestion: function() {
var self = this;
this.store.find('suggestion').then(function(s) {
self.controller.set('suggestion', s.get('firstObject'));
});
}
}
You should set the 'suggestion' inside 'then' block 你应该在'then'区块内设置'suggestion'
App.IndexRoute = Ember.Route.extend({
setupController: function(controller, model) {
this._super(controller, model);
controller.set('suggestion', null);
},
actions: {
getSuggestion: function() {
controller = this.controller;
this.store.find('suggestion').then(function(s) {
suggestion = s.get('firstObject');
controller.set('suggestion', suggestion);
});
}
}
});
You can change controller variable between controllers, 您可以在控制器之间更改控制器变量
If you want to change controller variable of "home" controller then you need to include Home controller into your controller. 如果要更改“home”控制器的控制器变量,则需要将Home控制器包含在控制器中。
Example:- 例:-
export default Ember.Controller.extend({
needs: ['home'],
changeVariable: function(){
if(..){
this.set('controllers.home.isMyHomePage', false);
}else{
this.set('controllers.home.isMyHomePage', true);
}
}
});
Could you do something like this with RSVP? 你能用RSVP做这样的事吗?
App.IndexRoute = Ember.Route.extend({
setupController: function(controller, model) {
this._super(controller, model);
controller.set('suggestion', null);
},
actions: {
getSuggestion: function() {
var suggestions = this.store.find('suggestion');
Ember.RSVP.all(suggestions).then(function(s) {
this.controller.set('suggestion', s.get('firstObject'));
}.bind(this));
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.