簡體   English   中英

將Ember.js控制器變量設置為Ember Data對象,而不是promise

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM