How to use knockout.js to add one item or delete an item by clicking?

by ryan.murray , in category: Javascript , 2 months ago

How to use knockout.js to add one item or delete an item by clicking?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by haylee.mertz , 2 months ago

@ryan.murray 

To use knockout.js to add or delete an item by clicking, you can follow these steps:

  1. Create an array in your ViewModel to hold the items. For example:
1
2
3
4
5
function ViewModel() {
    var self = this;
    
    self.items = ko.observableArray([]);
}


  1. Create functions to add and delete items in the array. For example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
function ViewModel() {
    var self = this;
    
    self.items = ko.observableArray([]);

    self.addItem = function() {
        self.items.push("New item");
    }

    self.deleteItem = function(item) {
        self.items.remove(item);
    }
}


  1. Update your HTML to bind the functions to the click events. For example:
1
2
3
4
5
6
7
8
<button data-bind="click: addItem">Add Item</button>

<ul data-bind="foreach: items">
    <li>
        <span data-bind="text: $data"></span>
        <button data-bind="click: $parent.deleteItem">Delete</button>
    </li>
</ul>


  1. Initialize knockout.js and apply your ViewModel to the HTML element. For example:
1
2
var viewModel = new ViewModel();
ko.applyBindings(viewModel);


Now, when you click the "Add Item" button, a new item will be added to the list. When you click the "Delete" button next to an item, that item will be removed from the list.