我正在尝试在javascript中创建一个ViewModel,viewmodel的一部分功能是从web加载数据并在ui端显示它。我遇到了一个问题,因为我无法在某个回调函数中引用viewmodel对象。情况如下:
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();
答案 0 :(得分:1)
你可以这样解决:
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方法。