KnockoutJS Click Binding

In the previous articles, we covered appearance and text bindings as well as control flow bindings. From this article onward, we shall see different types of form field bindings. These are the type of bindings that are associated with the behavior of different form fields. In this article we shall study KnockoutJS click binding.

Basically knockoutJS click binding allows us to attach click event of any HTML DOM element to a function or event handler in JavaScript view model. Usually click event for button, links or list items is handled. Take a look at the following example to see click binding in action.

KnockoutJS Click Binding Example

<!DOCTYPE html>
<html>
    
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
    
</head>

<body>
    

    <ul data-bind="foreach: fruits">
    <li>
        <span data-bind="text: $data"></span>
        <button data-bind="click: $parent.removeFruits">Remove Fruit</button>
    </li>
</ul>
 
 <script type="text/javascript">
     function FruitModel() {
         var self = this;
         self.fruits = ko.observableArray(['Apple', 'Orange', 'Banana','Guava', 'Peach']);
 
         // The current item will be passed as the first parameter, so we know which place to remove
         self.removeFruits = function(fruit) {
             self.fruits.remove(fruit)
         }
     }
     ko.applyBindings(new FruitModel());
</script>
    
</body>
</html>

Download the code Try the code

Take a careful look at the above code, lots of things are happening in it. First have a look at the HTML view section. Here we have list which uses foreach binding to iterate over fruits array. Inside the list we have a span tag which displays the name of the fruit and a button tag where we bind the click event of the button to the “removeFruits” function in the view model.

Now come down to the view model. Here we have a FruitModel which contains an observable fruits array with five fruits. Next we have a function “removeFruits” that takes name of a fruit and removes that fruit from the list. At

Now open the page in the browser, here you shall see five fruit names with five buttons. It is very interesting to note here that each button contains the data of the corresponding fruit. For instance if you click the button in front of button, the click event fires and banana is passed to the removeFruits function which removes banana from the fruits array. Since, fruits array is observable the front end or html view is updated immediately banana along with its remove button disappear from the list.

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .