Set Ember.js controller variable to Ember Data object, not a promise

I have a route that initially has no suggestion. Based on the action, I would like to grab an array of sentences from Ember Data, get the first sentence, and assign it to a controller. Here's what I have:

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 variable is still a promise suggestion

after performing the action getSuggestion

. How can I only set the controller variable after the promise is resolved? Or how can I let it resolve afterwards and update the variable with the actual object?

+3


source to share


4 answers


You have to set 'clause' 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);
      });
    }
  }
});

      

+1


source


Set the promise-resolved property:



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

      

+2


source


You can change the controller variable between controllers,

If you want to change the controller variable of a "home" controller, you need to include the Home controller in 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);
    }    
  }

});

      

+1


source


Could you do something similar 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));
    }
  }
});

      

0


source







All Articles