我在以下 JavaScript 中收到意外的 this
类型:
var MyReservationsViewModel = (function () {
function MyReservationsViewModel() {
this.availableMeals = [
{ mealName: "Standard (sandwich)", price: 0 },
{ mealName: "Premium (lobster)", price: 34.95 },
{ mealName: "Ultimate (whole zebra)", price: 290 }
];
this.self = this;
this.self.seats = ko.observableArray([
new SeatReservation("Steve", this.availableMeals[0]),
new SeatReservation("Bert", this.availableMeals[0])
]);
}
MyReservationsViewModel.prototype.addSeat = function () {
this.self.seats.push(new SeatReservation("", this.availableMeals[0]));
};
MyReservationsViewModel.prototype.removeSeat = function (seat) {
this.self.remove(seat);
};
return MyReservationsViewModel;
})();
;
var SeatReservation = (function () {
function SeatReservation(name, initialMeal) {
var _this = this;
this.name = name;
this.meal = ko.observable(initialMeal);
this.formattedPrice = ko.computed(function () {
var price = _this.meal().price;
return price ? "$" + price.toFixed(2) : "None";
});
}
return SeatReservation;
})();
var seat = new MyReservationsViewModel();
ko.applyBindings(seat);
我收到的异常是:
MyReservationsViewModel.prototype.removeSeat = function (seat) {
this.self.remove(seat);
};
问题是这是一种 SeatReservation
它的 HTML 页面是:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<h2>Your seat reservations</h2>
<table>
<thead>
<tr>
<th>Passenger name</th>
<th>Meal</th>
<th>Surcharge</th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: seats">
<tr>
<td><input data-bind="value: name" /></td>
<td><select data-bind="options: $root.availableMeals, value: meal, optionsText: 'mealName'"></select></td>
<td data-bind="text: formattedPrice"></td>
<td><a href="#" data-bind="click: $root.removeSeat">Remove</a></td>
</tr>
</tbody>
</table>
<button data-bind="click: addSeat">Reserve another seat</button>
<script src="Scripts/knockout-3.2.0.js"></script>
<script src="Scripts/MySeatReservation.js"></script>
</body>
</html>
最佳答案
在 knockout 中,传递给 click
绑定(bind)的函数上下文是绑定(bind)所在的 $data
。在您的例子中,您正在迭代 SeatReservation
类型的对象,因此这就是您的 $data
以及您的函数上下文。如果你想绑定(bind)到不同上下文中的函数,你可以这样做:
data-bind="click: $root.removeSeat.bind($root)"
另一种解决方案,可以更好地展示幕后发生的事情,是制作一个备用 custom binding看起来像这样:
data-bind="clickWithRootContext: $root.removeSeat"
您几乎可以复制现有的 click binding 的方式有效并更改我突出显示的行上的上下文(我相信 this
变成 bindingContext.$root
)。
实际上,我喜欢这个想法,所以我打算将其添加到我的自定义绑定(bind)库中(谢谢:))。对其他似乎正确的答案感到抱歉,我试图提供一个更简单的解释。
关于javascript - javascript 中出现意外的此类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27204572/