goal
Remove items from an external observable array using KnockoutJS.
Problem
There are two observableArray in my application. One for the available products for purchase and other products that I added to the resume by clicking the add button .
So far, everything is working fine here. But now I need to remove the elements from the Summary and change the state / style of the button - and I donβt know how to access the external observableArray for this.
To understand my problem, check out this jsFiddle or view the markup in the next section.
As you can see, when I click add button , the product goes to the summary. When I click on delete β regardless of whether the button is from the bulletin or the product β I want to change the state of the button and remove the item from the bulletin. Technically speaking, I want to remove an item from items' observableArray using products' observableArray .
My code
HTML:
<ul class="summary"> <p data-bind="text: name"></p> <button class="btn btn-danger btn-mini remove-item"> <i class="icon-remove">Γ</i> </button> </ul> <h1>What would you to buy?</h1> <ul class="products"> <li> <h3 data-bind="text: name"></h3> <p data-bind="text: desc"></p> <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> <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> </li> </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);
source share