我有一个品牌列表,品牌包含汽车列表。在http://jsfiddle.net/PZqEk/1/的淘汰赛中声明了简单的视图模型。单击删除按钮时,在 removeCar 函数中未定义 this.cars。如何使用最佳实践删除点击的汽车?
html:
<h1 data-bind="text:title"></h1>
<table>
<tbody data-bind="foreach: brands">
<tr>
<td>
<span data-bind="text: nameOfBrand"></span>
<ul data-bind="foreach: cars">
<li>
<span data-bind="text: nameOfCar"></span>
(<span data-bind="text: yearOfCar"></span>)
<input data-bind="click: $root.removeCar" type="button" value="remove"/>
</li>
</ul>
</td>
</tr>
</tbody>
</table>
Javascript:
function RootModel()
{
this.title = ko.observable("Dummy Title");
this.brands = ko.observableArray();
var b1 = new brandModel("Audi");
b1.cars.push(new carModel("A3", 2005));
b1.cars.push(new carModel("A6", 2005));
var b2 = new brandModel("Volkswagen");
b2.cars.push(new carModel("Golf", 2010));
b2.cars.push(new carModel("Passat", 2008));
b2.cars.push(new carModel("Polo", 2012));
this.brands.push(b1);
this.brands.push(b2);
}
function brandModel(name)
{
this.nameOfBrand = ko.observable(name);
this.cars = ko.observableArray();
this.removeCar = function(car){
this.cars.remove(car); // this.cars = undefined;
}
}
function carModel(name, year){
this.nameOfCar = ko.observable(name);
this.yearOfCar = ko.observable(year);
}
ko.applyBindings(new RootModel());
谢谢