将Ember.js控制器变量设置为Ember Data对象,而不是promise

时间:2015-05-13 14:59:47

标签: javascript ember.js ember-data 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之后才设置控制器变量?或者我怎样才能让它在事后解决并使用实际对象更新变量?

4 个答案:

答案 0 :(得分:2)

根据承诺的解决方案设置属性:

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

答案 1 :(得分:1)

您应该设置'建议'在里面'然后'块

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

答案 2 :(得分:1)

您可以在控制器之间更改控制器变量,

如果你想改变" home"的控制器变量。控制器然后你需要将家庭控制器包含在你的控制器中。

实施例: -

export default Ember.Controller.extend({

  needs: ['home'],
  changeVariable: function(){
    if(..){
      this.set('controllers.home.isMyHomePage', false);
    }else{
      this.set('controllers.home.isMyHomePage', true);
    }    
  }

});

答案 3 :(得分:0)

你能用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));
    }
  }
});