如何在嵌套的observable数组中调用knockout函数

时间:2013-03-05 19:04:52

标签: knockout.js

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

由于

2 个答案:

答案 0 :(得分: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
    }
}

答案 1 :(得分:0)

Jeff是正确的,你应该为this设置别名(通常在模型顶部声明self = this;),我建议你为每个Knockout应用程序执行此操作。

但是,我没有注意到您最初使用的是this,并立即尝试了此代码:

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

并且作为你小提琴的唯一改变,这是有效的。