Reputation: 95
I'm struggling with how to best represent my data with Knockout. Is it better to have a master viewmodel that contain children viewmodels or to have only one master viewmodel? Here is an example of the way may data is represented:
Company { CompanyID, Industry, Name, Address, Phone }
Employee { CompanyID, EmployeeID, Name, Address, Phone }
There can be many companies and each company can have many employees. I need the user to be able to select a company from a pull-down, have the company record fill in, then show the list of employee records. If the company record is changed, I only want to send back the company record (via jSON) to the server. If an employee record is change, I only want to send the employee record back to the server.
Of course, there can be no Employee
records loaded until after a Company
record is loaded.
Upvotes: 0
Views: 268
Reputation: 22338
Try not to think about "better" ... instead think about what your View needs. Build a viewmodel for it with the models that it needs. if you need a list of companies, to select a company, then to show a list of employees all in one View then you could have a viewmodel which exposes this hierarchy of models.
Or you could create multiple Views: 1 for selecting the company from a list, 1: for show company details, 1: for selecting employees ... you get the idea. Then each view has its own viewmodel with that data.
Or you can create a master viewmodel with sub viewmodels.
I usualyl start with 1 View and 1 ViewModel and only split amongst several once I get to a point where it feels like the ViewModel (or view) is getting heavy.
Upvotes: 1