从可观察数组中删除项目

时间:2015-03-29 17:35:02

标签: knockout.js

http://jsfiddle.net/jkittell/d8thwnqg/5/

在我的代码中,我要删除的项目是未定义的。

<p><span data-bind='text: fullName'></span>'s Shopping Cart</p>
<table>
    <thead><tr>
        <th>Product</th>
        <th>Price</th>
        </tr></thead>
    <tbody data-bind='foreach: shoppingCart'>
        <tr>
            <td data-bind='text: name'></td>
            <td data-bind='text: price'></td>
        </tr>
    </tbody>
</table>

<button data-bind='click: addProduct'>Add</button>
<button data-bind='click: $root.removeProduct'>Remove</button>
<button data-bind='click: checkout'>Checkout</button>

如何设置product变量以从可观察数组中删除项目?

function Product(name, price) {
        this.name = ko.observable(name);
        this.price = ko.observable(price);
    }

function vm() {
    var self = this;
    this.firstName = ko.observable("John");
    this.lastName = ko.observable("Smith");
    self.fullName = ko.computed(function() {
        return this.firstName() + " " + this.lastName();
    }, this);
    this.shoppingCart = ko.observableArray([
        new Product("Beer", 10.99),
        new Product("Brats", 7.99),
        new Product("Buns", 1.49)
    ]);
    this.addProduct = function() {
        this.shoppingCart.push(new Product("More Beer", 10.99));
    };
    this.removeProduct = function(product) {
        alert("removing: " + product.name);
        self.shoppingCart.remove(product);
    };
    this.checkout = function() {
        alert("Checking out");
    };
}

ko.applyBindings(new vm());

1 个答案:

答案 0 :(得分:1)

你的&#39;删除&#39;按钮是在淘汰赛foreach绑定之外(因此,当你点击它时,你希望删除哪个项目?)。

你需要把它放在foreach绑定中:

<tbody data-bind='foreach: shoppingCart'>
    <tr>
        <td data-bind='text: name'></td>
        <td data-bind='text: price'></td>
        <td><button data-bind='click: $root.removeProduct'>Remove</button></td>
    </tr>
</tbody>

见工作fiddle

如果您想拥有一个按钮,请说明您需要做什么(删除最后一项?)。

相关问题