在承诺成功后,无法在ember中设置属性

时间:2014-09-29 23:21:12

标签: javascript ember.js ember-data

当promise成功并且我尝试使用this.set('propertyName', value)设置控制器的属性时,我收到有关set方法的以下错误:

  

TypeError:undefined不是函数

模板:

<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>

应用程序控制器:

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

一旦承诺成功或有关范围的其他问题,是否有新的范围?

1 个答案:

答案 0 :(得分:3)

通常,您必须假设回调(不仅仅是promises,所有回调)都会丢失this指针的值,除非文档另有说明。这种行为是因为调用者决定了this指向的内容,在这种情况下,调用者是Ember正在使用的任何promise库中的then函数。

解决方案是在闭包中捕获this,如下所示:

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