Reputation: 5001
Switch between add/remove button based on availability using KnockoutJS.
I need to add a product/item to my summary. If the product is already on summary, then changes the "add button" into "remove button" or else changes from "remove button" to "add button"
Until here, just concept, right? Yea, but I think I'm missing the logic of the trouble.
Look:
<!-- ko foreach: products -->
<!-- ko if: isAdded -->
<button class="btn btn-small btn-success action remove">
<i class="icon-ok"></i>
</button>
<!-- /ko -->
<!-- ko ifnot: isAdded -->
<form action="#" data-bind="submit: add">
<button class="btn btn-small action add">
<i class="icon-plus"></i>
</button>
</form>
<!-- /ko -->
<!-- /ko -->
As you can see, there is conditions to check if a specific product is added or not. If the list is empty, nothing appears; If I add something manually by code, the two buttons appears — remove and add button.
I made this CodePen to simulate the scenario.
Can someone help me?
I can use jQuery; I'm already working on it for about three weeks and until now, no success.
Upvotes: 2
Views: 211
Reputation: 11977
In my opinion you don't take full advantage of knockoutjs (but that could just be because I don't see the full application). I however rewrote it a bit and put up an example here (jsfiddle).
function Product(name, desc) {
var self = this;
self.name = ko.observable(name);
self.desc = ko.observable(desc);
self.isAdded = ko.observable(false);
};
function SummaryViewModel(products) {
var self = this;
self.products = ko.observableArray(products);
self.add = function (item) {
var i = self.products.indexOf(item);
self.products()[i].isAdded(true);
};
self.remove = function (item) {
var i = self.products.indexOf(item);
self.products()[i].isAdded(false);
};
};
var p = [new Product("One", "Yep one"), new Product("Two", "nope, two")];
ko.applyBindings(new SummaryViewModel(p));
Upvotes: 1