In the last few posts on knockout we’d explored already a lot of KnockoutJS, in this post we will look at yet another important binding, the parent level binding. The parent binding is the binding of the View’s items, with the properties present at the root level of the ViewModel. To understand this concept, let us take a simple example.
Consider a web application, having the names of popular Indian dishes displayed onto the screen.
If you have read my previous posts on Knockout, creating this kind of application is mere a five minute task. If you look at the snap above, you can see a “Remove” button corresponds to every item. The “Remove” button simply removes the corresponding entry from the list. Here is the View and the ViewModel’s code for that.
1: var ViewModel = function(){
2:
3: var self = this;
4:
5: self.foodItems = ko.observableArray(['Paneer','Pizza','Gobhi','Chhole']);
6:
7: }
8:
9: ko.applyBindings(new ViewModel());
1: <html xmlns="http://www.w3.org/1999/xhtml">
2:
3: <head>
4: <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5: <title>Untitled Document</title>
6: </head>
7:
8:
9: <body>
10:
11: <div data-bind="foreach: foodItems">
12: <span data-bind="text: $data"></span>
13: <button>Remove</button><br/>
14: </div>
15:
16: <script src="js/knockout 3.0.0.0.js"></script>
17: <script src="js/ViewModel.js"></script>
18:
19:
20: </body>
21: </html>
The Code for removing the entry from the list would be like:
1: this.RemoveClicked = function(arg){
2: self.foodItems.remove(arg);
3: }
Now if you analyze the “View” closely, you will see that the division which is encapsulating the remove button is bind with an observable array foodItems. So, you cannot bind the button’s click event to the RemoveClicked method directly. That is to say, writing data-bind=”click: RemoveClicked” will not work.
Since our method “RemoveClicked” is at the parent level, so what best we can do is we can apply the root level binding. Therefore, instead of writing :
1: <button data-bind="click: RemoveClicked">Remove</button>
We can write:
1: <button data-bind="click: $root.RemoveClicked">Remove</button>
What this does is it simply binds the click of the button to the method which is present at the root level of viewmodel.
You can also user $parent instead of $root to do a root level binding, both are equally acceptable.
Happy Coding!!!
0 comments