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.

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.