Javascript Backbone.sync作用域问题

Javascript Backbone.sync作用域问题,javascript,backbone.js,scope,Javascript,Backbone.js,Scope,我目前正在使用backbone.sync将我的收藏发送到一个PHP函数,该函数将我的信息存储在数据库中,并根据his返回一些数据 在my.sync()的成功功能之前,一切都正常,因为我失去了模型和集合的作用域,因此无法更新它们,有什么办法可以解决这个问题吗 我试过使用两种方法,但都没有返回任何结果,我在这里或谷歌上找不到更多关于这个主题的信息。我的首选项还包括避免使用model.save(),因为对后端的调用太多 方法1 var that=this; // some logic is done

我目前正在使用
backbone.sync
将我的收藏发送到一个PHP函数,该函数将我的信息存储在数据库中,并根据his返回一些数据

在my
.sync()
的成功功能之前,一切都正常,因为我失去了模型和集合的作用域,因此无法更新它们,有什么办法可以解决这个问题吗

我试过使用两种方法,但都没有返回任何结果,我在这里或谷歌上找不到更多关于这个主题的信息。我的首选项还包括避免使用
model.save()
,因为对后端的调用太多

方法1

var that=this;
// some logic is done here
backbone.sync("update",this.collection,{
    success:function(data){
        // attempt to update this.collection here, but `that` is out of scope
        // and the scope of `this` is different 
    }
});
方法2:

var that=this;
var onDataHandler=function(data){
    // attempt to update this.collection here, but `that` is out of scope
    // and the scope of `this` is different 
};
// some logic is done here
backbone.sync("update",this.collection,{
    success:onDataHandler
});
有人知道解决这个问题的方法吗?我查看了主干文档,发现
collection.fetch()
函数将委托给
.sync()
,但是第二种方法是我用于
.fetch()
的方法,它可以很好地保持
的范围,即
尝试:

var that=this;
var prebindHandler=function(data){
    // attempt to update this.collection here, but `that` is out of scope
    // and the scope of `this` is different 
};
successHandler = prebindHandler.bind(this);
// some logic is done here
backbone.sync("update",this.collection,{
    success:successHandler
});

这很好用。非常感谢,以前没有听说过.bind()方法,所以现在我将详细阅读。几分钟内我不会接受你的答案,但我会在我能接受的时候接受。是的,关于JavaScript中的作用域也值得多读一点。