How do I remove an object from an array of objects. in knockoutJS. Error: Object doesn't support property or method 'remove'

How do I remove an object from an array of objects. in knockoutJS. Error: Object doesn't support property or method 'remove'

如何从 Knockoutjs 中的对象数组中删除对象。 我是 knockoutjs 的新手,我们将不胜感激。

A link to Jsfiddle

js上HTML代码中第24行fiddle是点击绑定删除。 js fiddle 上的 javascript 代码中的第 67 行是创建从数组中删除对象的函数的地方。 我尝试在第 68 行和第 69 行使用 indexOf 和 splice Array 函数,它可以删除但 DOM 没有被更新。 请看一下函数 removeProduct: function (product)

Html

<div>List of Product (<span data-bind="text: products().length"></span>) 
</div>
<ul data-bind="foreach: products">
    <li><span data-bind="text:name"></span>
        <a href="#" data-bind="click: $root.removeProduct">Select</a>
    </li>

</ul>
<div>List of Group Ideas</div>
<ul data-bind="foreach: GroupIdeas">
    <li data-bind="text:name">
        <input type="button" value="Removethis" />
        <input type="button" value="vote" />
    </li>

</ul>
<div>List of Group members</div>
</body>

 Javascript



$(function () {
var viewModel = {
    productPrice: ko.observable(89),
    productQty: ko.observable(2),

    products: ko.observable([
        { name: "shoe", price: "788", id: 1 },
        { name: "blouse", price: "50", id: 2 },
        { name: "dress", price: "16", id: 3 },
        { name: "lipstick", price: "88", id: 4 },
        { name: "earring", price: "4", id: 5 },
        { name: "bra", price: "96", id: 6 },
        { name: "lingeringe", price: "48", id: 7 },
        { name: "neclace", price: "36", id: 8 },
    ]),
    GroupIdeas: ko.observable([
        { name: "shoe", price: "788", prodId: 1, selectedby: "Akuba", memId: 
1, votes: 3 },
        { name: "lingeringe", price: "48", prodId: 7, selectedby: "Isaac", 
memId: 2, votes: 6 },
    ]),
    GroupMember: ko.observable([
        { name: "Akuba", relation: "friend", id: 1 },
        { name: "Isaac", relation: "Husband", id: 2 },
        { name: "Ira", relation: "Sister", id: 3 },
        { name: "Davida", relation: "Mum", id: 4 }
    ]),
    partyPerson: ko.observable("Ida"),
    partyOrganiser: ko.observable("Royce"),
    //addProduct = function () { /* ... leave unchanged ... */ }
    removeProduct: function (product) {
        /*var indexArr = viewModel.products().indexOf(product);
        viewModel.products().splice(indexArr, 1)
        */

        viewModel.products().remove(product)
        console.log(product);
    }
};

  viewModel.totalAmt = ko.computed(function () {
      return this.productPrice() * this.productQty();
   }, viewModel);


ko.applyBindings(viewModel);
//ko.applyBindings(giftModel);
})**

这是你的updated fiddle

  1. 您需要使 products 成为可观察数组才能利用 remove 函数。

  2. 您需要先引用视图模型才能引用products,因此您的removeProduct函数必须在视图模型初始化之后编写。类似于你写的 totalAmt.

    viewModel.removeProduct = function (product) {
         viewModel.products.remove(function(item){
             return item.id === product.id;
         });
    }