2015-04-23 51 views
0

我有一个简单的嵌套查询,但我无法弄清楚如何将“this”变量绑定到成功块。我包含一些额外的代码行,以提供更多的上下文。parse.com将此绑定到成功块

initialize: function() { 

     _.bindAll(this, 'addAll', 'addOne', 'logOut', 'newJob', 'showDetail'); 

     this.$el.html(_.template($("#manage-jobs-template").html())); 

     this.jobs = new JobList; 
     this.requests = new RequestList; 

     this.jobs.query = new Parse.Query(Job); 
     this.jobs.query.equalTo('jobPostedBy', Parse.User.current()); 
     this.jobs.fetch({ 

      success: function (jobs) { 
      //This is undefined here. 
      this.requests.query = new Parse.Query(Request); 
      this.requests.query.containsAll("job", jobs); 
      this.requests.fetch(); 
      } 

    }); 

回答

1

一个可能的解决方案是将引用保存到thisinitialize函数内部,然后在您的success功能使用它。 self将可里面success

initialize: function(){ 
    var self = this; 
    ... 
    this.jobs.fetch({ 
     success: function(jobs){ 
      self.request.query = ... //--- here self references the "outer" this 
      .... 
     } 
    }); 
} 

另一个解决方案是结合上下文匿名函数bind()

initialize: function(){ 
    ... 
    this.jobs.fetch({ 
     success: (function(jobs){ 
      this.request.query = ... 
      .... 
     }).bind(this); //--- context binding 
    }); 
} 

看看这个例子:https://jsfiddle.net/8e8yfxx9/3/

+0

这正是我在寻找!! +1两种解决方案。现在关闭调查为什么containsAll不工作:)).... – Mika