parse.com将此绑定到成功块

时间:2015-04-23 12:00:50

标签: javascript parse-platform

我有一个简单的嵌套查询,但我无法弄清楚如何绑定"这个"变量到成功块。我提供了一些额外的代码行来提供更多的上下文。

  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 个答案:

答案 0 :(得分:1)

一种可能的解决方案是在this函数中保存对initialize的引用,然后在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/