4

目标

使用 KnockoutJS 从外部 observableArray 中删除项目。

问题

我的申请中有两个observableArray。一个用于可供购买的产品,另一个用于我通过单击在摘要中添加的产品add button

直到这里,一切正常。但现在我需要从摘要中删除项目并更改按钮状态/样式——我不知道如何访问外部observableArray来执行此操作。

要了解我的问题,请查看此 jsFiddle或查看下一个主题中的标记。

如您所见,当我单击 时add button,产品转到摘要。当我单击删除时——无论按钮来自摘要还是产品——我都想更改按钮状态并从摘要中删除该项目。从技术上讲,我想从items' observableArray使用products' observableArray.

我的代码

HTML:

<ul class="summary">
    <!-- ko foreach: Summary.items -->
        <p data-bind="text: name"></p>
        <button class="btn btn-danger btn-mini remove-item">
            <i class="icon-remove">×</i>
        </button>
    <!-- /ko -->
</ul>

<h1>What would you to buy?</h1>

<ul class="products">
    <!-- ko foreach: Product.products -->
    <li>
        <h3 data-bind="text: name"></h3>
        <p data-bind="text: desc"></p>
        <!-- ko if:isAdded -->
        <button data-bind="if: isAdded" class="btn btn-small btn-success action remove">
            <i data-bind="click: $root.Summary.remove" class="icon-ok">Remove</i>
        </button>
        <!-- /ko -->
        <!-- ko ifnot:isAdded -->
        <form data-bind="submit: function() { $root.Summary.add($data); }">
            <button data-bind="ifnot: isAdded" class="btn btn-small action add">
                <i class="icon-plus">Add</i>
            </button>
        </form>
        <!-- /ko -->
    </li>
    <!-- /ko -->
</ul>

JavaScript:

function Product(id, name, desc) {
    var self = this;

    self.id = ko.observable(id);
    self.name = ko.observable(name);
    self.desc = ko.observable(desc);
    self.isAdded = ko.observable(false);
}

function Item(id, name) {
    var self = this;

    self.id = ko.observable(id);
    self.name = ko.observable(name);
}

function SummaryViewModel() {
    var self = this;
    self.items = ko.observableArray([]);

    self.add = function (item) {
        self.items.push(new Item(item.id(), item.name()));

        console.log(item);

        item.isAdded(true);
    };

    self.remove = function (item) {
        item.isAdded(false);
    };
};

function ProductViewModel(products) {
    var self = this;

    self.products = ko.observableArray(products);
};

var products = [
    new Product(1, "GTA V", "by Rockstar"), 
    new Product(2, "Watch_Dogs", "by Ubisoft")
];

ViewModel = {
    Summary: new SummaryViewModel(),
    Product: new ProductViewModel(products)
}

ko.applyBindings(ViewModel);
4

2 回答 2

10

你可以搜索它

您可以在购物车中查询具有相同 id 的商品,然后将其删除

self.remove = function (item) {
    var inItems = self.items().filter(function(elem){
        return elem.id() === item.id(); // find the item with the same id
    })[0];
    self.items.remove(inItems);
    item.isAdded(false);
};

除非您有数十万个项目,否则这应该足够快。只要记住使用items.remove()它就会知道更新observableArray:)

于 2013-07-09T20:52:25.517 回答
1

一旦您将 products 声明为 observableArray,您就应该能够在其上调用 remove(根据this)。假设您有对要删除的对象的引用以传入。

于 2013-07-09T21:00:52.620 回答