使用绑定函数维护原始回调"this"



我知道bind创建了一个替换this值的新函数。示例

function edit(req, res) {
db.User.findById('ABCD', (function(err, user){
this.foo(user);
}).bind(this));
};

从 在使用回调和闭包时维护对 Javascript 中"this"的引用

具有提供自己的参数的回调函数。

我正在使用http.min.js,它处理这样的回调:

http.get({
url: "http://localhost:8080/player/status/" + name,
onload: function() {
console.log(this.responseText);

请注意缺少传入的内容 -this.responseText会给我一个可以解析JSON的字符串。

从回调http.min.js中维护"this"并绑定到我的回调函数的最简单方法是什么?

我喜欢的语法

http.get({
url: "http://localhost:8080/player/status/" + name,
onload: this.handlePlayerInfo.bind(this);

如果可能的话,想要使用它,而不是使用var that.

使用库:https://github.com/quantumpotato/http.min.js/blob/master/http.min.js

看起来使用var that是维护回调"this"状态的唯一方法。

所以我会做的

Callback.hell = this;
http.get({
url: "http://localhost:8080/join/" + Player.name,
onload: this.handleJoin;
});
handleJoin(res) {
var json = JSON.parse(JSON.parse(this.responseText));
console.log("join" + j);
console.log(j.name);
Callback.hell.status.auth = j.auth;
Callback.hell.status.name = j.name;
Callback.hell.getPlayerInfo();
}

最新更新