[英]Set an Ember.js controller variable to an Ember Data object, not a promise
我有一条最初没有任何建议的路线。 基于动作,我想获取一个带有Ember Data的建议数组,得到第一个建议并将其分配给控制器。 这是我得到的:
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);
}
}
});
问题是suggestion
变量在执行getSuggestion
操作后仍然是一个promise。 如何在解析promise之后才设置控制器变量? 或者我怎样才能让它在事后解决并使用实际对象更新变量?
根据承诺的分辨率设置属性:
actions: {
getSuggestion: function() {
var self = this;
this.store.find('suggestion').then(function(s) {
self.controller.set('suggestion', s.get('firstObject'));
});
}
}
你应该在'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);
});
}
}
});
您可以在控制器之间更改控制器变量
如果要更改“home”控制器的控制器变量,则需要将Home控制器包含在控制器中。
例:-
export default Ember.Controller.extend({
needs: ['home'],
changeVariable: function(){
if(..){
this.set('controllers.home.isMyHomePage', false);
}else{
this.set('controllers.home.isMyHomePage', true);
}
}
});
你能用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.