简体   繁体   中英

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. 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. How can I only set the controller variable after the promise is resolved? 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

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.

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM