One of the things we’ll probably need is to be able to have dependency tracking in our bounded data. For example – if we have a customer’s list, we’d like to see the customer’s orders whenever we click on a customer. In this post I’ll demonstrate how to do it using the dependentObservable function of KnockoutJS
In here, I’ve declared two data structures: customer and order. I’ve also exposed two data members: customers and orders which have the types above respectively. I’ve also exposed the selectedCustomer data-member which will be used for us in the future.
Now, let’s go to our HTML content.
In here we’ll have two tables – one for customers and one for orders. We’ll use templates for our data binding so it will look like that:
You can notice from the HTML another three things:
1. There’s a button to add customer, when clicked it calls the addCustomer function
2. There’s a button to add order, when clicked it calls the addOrder function.
3. Whenever a customer row clicked, the setSelectedCustomer function is called.
All setSelectedCustomer does is assign the customer who’s row was clicked on, to the
selectedCustomer data member. The dependentObservable function will do the rest.
Now, Let’s have dependencies between the selected costumer and it’s orders:
What does it do? whenever the selectedCustomer member is changed, it assigns it’s orders to the orders data member, and that’s how we’ve achieved dependencies between the customer and it’s order.
In the function of it’s first parameter, we can have all our dependency tracking code (and that’s all our dependency tracking). The word “this” inside the function refers to the view-model we’ve provided on the second parameter.
Dependency tracking is something we’d probably want when having data binding with complex data (parent-child structures for example), having master-details view or even computed values. The dependentObservable function of KnockoutJS allows as to do so in a very easy manner. All we have to do is plant our code in the function at it’s first parameter and well… that’s it.
Here is the full example: