I need to call multiple web services to get different bits of information about a resource. For instance I may have the following calls for a multi-tenant app:
- GET locations
- GET locations/{id}/servers
- GET locations/{id}/tenants
- etc.
With each of these calls I end up with a different jQuery ajax call to a corresponding web service. However my UI displays a summary page of sorts that displays a table for the results from each query. It seems it would be really easy to build a single Knockout ViewModel that then has ObservableArrays for each query result but maybe I’m approaching this incorrectly. Either way I’m not sure how to consolidate the multiple calls to one model or utilize multiple models for each call.
Does anyone have any documentation or sample code they could share to point me in the right direction?
Update: I want to acheive this end result/structure in my Knockout object. Essentially it is a one to many relationship, one location to many servers or tenants.
LOCATION
- Name
- ID
- Date
- Servers []
- Tenants []
Thanks
What I do is create one view model for the page and update the properties with the values from each call. I use the ko.mapping plugin with three parameters to update the existing observable array and make the properties observable. The
ko.mapping.fromJSONcalls will go in the success function of your AJAX call where you get the results, I just made them click handlers for simplicity.http://jsfiddle.net/jgoemat/v9XTf/
edit – Updated Fiddle
If the locations contain the tenants, you can modify that property on the location, the ko event handler passes the current model to the handler:
If you’re binding with jQuery, you can use
ko.dataFor(element)to get the model from the context where the element is: