0

我有一个品牌列表,品牌包含汽车列表。在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());

谢谢

4

2 回答 2

1

问题是您正在this从未在实例上调用的函数访问。你需要一个别名。

function brandModel(name) {
    var self = this; // alias
    self.nameOfBrand = ko.observable(name);
    self.cars = ko.observableArray();

    self.removeCar = function(car) {
        self.cars.remove(car); // access through the alias instead
    }
}
于 2013-03-05T19:09:50.447 回答
0

Jeff 是正确的,因为您应该使用别名this(通常通过self = this;在模型顶部声明),我建议对您制作的每个 Knockout 应用程序都这样做。

但是,我一开始并没有注意到你在使用this,并立即尝试了这段代码:

<input data-bind="click: function(data, event) { $parent.removeCar(data); }" type="button" value="remove"/>

作为你小提琴的唯一改变,它奏效了。

于 2013-03-05T19:18:12.190 回答