所以我建立一个Javascript路由器,建设这样的路线:如何将范围保留在XHR请求中?
route('/user/{name}', 'page', function() {
this.text = 'User: ' + this.name;
});
功能的范围是当前的路线,所以我在这里可以操纵当前路由(this.text是观点是什么寻找)。现在
我的下一个步骤是包括路线中的一个XHR请求,这看起来是这样的:
route('/user/{name}', 'page', function() {
this.text = 'Loading';
var request = new XMLHttpRequest();
request.open('GET', '/api/user', true);
request.onreadystatechange = (function() {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
var data = JSON.parse(this.responseText);
// here is the issue: 'this' now refers to
// the XHR request and not the scope of the router
this.age = data.age;
this.gender = data.gender;
} else {
this.text = "Error";
}
}
})/* .bind(this); */ // keeping scope like this overwrites the XHR
request.send();
request = null;
});
这里的问题是,我需要访问XHR范围和我的路由器的范围。在onreadystatechange末尾使用.bind会覆盖XHR范围,并且不会覆盖路由器的范围。
so wat do?有什么比var that = this;
更清洁的 - 肯定有办法吗?
广东话”你只是删除了'this'从'this.age'和'this.gender'? –
为什么不能:'var that = this;'?它可能不是最优雅的方式,但它的工作原理... –
这只是我的问题,是否有一个更清晰的方法来保持范围。 Buuut我猜想没有办法避免它,因为'this'会用'this'进行分类,也许解决方案将是设置默认范围变量的一种方法。不过谢谢@ChrisL和迷宫乐。 – bitten