将Ember.js控制器变量设置为Ember数据对象,而不是承诺



我有一条最初没有建议的路线。根据操作,我想抓住一个带有Ember数据的建议数组,获取第一个建议并将其分配给控制器。这是我得到的:

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操作后,它仍然是一个承诺。解决承诺后,我如何才能设置控制器变量?或者如何让其后来解决并使用实际对象更新变量?

将属性设置为诺言的分辨率:

actions: {
    getSuggestion: function() {
        var self = this;
        this.store.find('suggestion').then(function(s) {
            self.controller.set('suggestion', s.get('firstObject'));
        });
    }
}

您应该将'建议'内部设置为'然后'块

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 Controller包含在控制器中。

示例: -

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));
    }
  }
});

最新更新