Can't set properties in ember after promise succeeds

When the promise succeeds and I attempt to set a property of the controller using this.set('propertyName', value) I get the following error regarding the set method:

TypeError: undefined is not a function

Template:

<script type="text/x-handlebars">
      <nav class="navbar navbar-default" role="navigation">
        <div class="container-fluid">
          <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse">
              <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="#">Qlovi Reader</a>
      </div>
      <div class="collapse navbar-collapse" id="navbar-collapse">
        <form class="navbar-form navbar-left" role="search"{{action 'updateInfo' on="submit" }}>
          <div class="form-group">
            {{input value=attemptQuestionSet type="text" class="form-control" placeholder="37297"}}
          </div>
          <button type="submit" class="btn btn-default">Submit</button>
        </form>
        {{#if currentUser}}
          <p class="navbar-text navbar-right">Signed in as {{currentUser.userName}}</p>
        {{/if}}
      </div>
    </div>
  </nav>
  <div class="container-fluid">
      {{outlet}}
  </div>
</script>

Application Controller:

 App.ApplicationController = Em.Controller.extend({
  currentQuestionSet: null,
  actions:{
    updateInfo: function(){
      this.store.find('questionSet', parseInt(this.attemptQuestionSet)).then(function(questionSet){
        this.set('currentQuestionSet',questionSet);
      },function(){
        alert("Question Set not found");
      });
    }
  }
});

Is there a new scope once the promise succeeds or other issues regarding scope?

Upvotes: 0

Views: 314

Answers (1)

Chris Tavares
Chris Tavares

Reputation: 30401

In general, you have to assume callbacks (not just promises, all callbacks) will lose the value of the this pointer unless documentations specifically says otherwise. This behavior is because the caller is what determines what this points to, and in this case the caller is the then function in whatever promise library Ember is using.

The solution is to capture this in a closure, like so:

 App.ApplicationController = Em.Controller.extend({
  currentQuestionSet: null,
  actions:{
    updateInfo: function(){
      var self = this; // Store away current this
      this.store.find('questionSet', parseInt(this.attemptQuestionSet)).then(function(questionSet){
        self.set('currentQuestionSet',questionSet); // <-- note use of stored reference
      },function(){
        alert("Question Set not found");
      });
    }
  }
});

Upvotes: 3

Related Questions