JavaScript 'this' 引用了错误的范围
javascript 'this' references wrong scope
我正在尝试在javascript中创建一个ViewModel,视图模型的部分功能是从Web加载数据并将其显示在UI端。我遇到了一个问题,因为我无法在某个回调函数中引用视图模型对象。情况如下:
LoggedInViewModel.prototype = {
getFriendList: function() {
var self = this; // 'this' references the correct viewmodel object
$.ajax({
url: "api/users/friendlist",
success: self.loadFriendListIntoModel
});
},
loadFriendListIntoModel: function (friends) {
var self = this;
//'this' references the ajax object that called the function.
// is there a way to make 'this' reference the actual viewmodel
// object here? i can do var self = model; but that feels hacky
friends.forEach(function (friend) {
//Uncaught TypeError: Cannot call method 'push' of undefined
self.friendList.push(new Friend(friend));
});
}
};
var model = new LoggedInViewModel();
ko.applyBindings(model);
model.getFriendList();
你可以这样修复它:
getFriendList: function() {
$.ajax({
url: "api/users/friendlist",
success: this.loadFriendListIntoModel,
context: this
});
},
或者像这样:
getFriendList: function() {
var self = this; // 'this' references the correct viewmodel object
$.ajax({
url: "api/users/friendlist",
success: function() {
self.loadFriendListIntoModel();
}
});
},
或者像这样:
getFriendList: function() {
$.ajax({
url: "api/users/friendlist",
success: $.proxy(this.loadFriendListIntoModel, this)
});
},
阅读 $.ajax 了解上下文选项和关于 $.proxy。你也可以使用Function.prototype.bind方法。
相关文章:
- 日志:未捕获的范围错误:超过了最大调用堆栈大小
- 未捕获的范围错误:setTimeout()超过了最大调用堆栈大小
- JavaScript继承:未捕获的范围错误:超过了最大调用堆栈大小
- 收到“范围错误: 超出最大调用堆栈大小”错误
- 范围错误与 mongo 进行$near查找
- 未捕获的范围错误:WebSQL查询结果中的项索引超出范围错误
- IE 8变量范围错误
- Chrome/jQuery未捕获范围错误:超过了最大调用堆栈大小(函数循环)
- AngularJS-范围错误:''之后超过了最大调用堆栈大小;应用程序启动
- javascript中的函数范围错误
- Chrome 未捕获范围错误:最大调用堆栈大小超出了点击递归
- 此节点范围错误背后的原因
- jquery .on 获取未捕获的范围错误:超出最大调用堆栈大小
- Babel/RequireJS + 类型“范围错误:超出最大调用堆栈大小”
- 范围错误:调用堆栈超出异步 .eachSeries 上的范围错误
- 复杂 JSON 处理期间的“范围错误: 超出最大调用堆栈大小”
- 范围错误:在 Javascript 中超出了最大调用堆栈大小
- 范围错误:超出最大调用堆栈大小(角度)
- 余烬错误 - 加载路由时出现“调用堆栈大小超出范围错误”
- 解决jQuery ui日期范围错误