I'm on my first Knockout project and working trying to figure out the best way to handle this situation.
Hopefully this dumbed down example serves it's purpose.
I am trying to edit a 'project' object which has a property for 'employee'.
function Project(data) {
var self = this;
self.Name = data.Name;
self.Employee = data.Employee;
}
function Employee(data) {
var self = this;
self.ID = data.ID;
self.Name = data.Name;
}
I first load up my project and then set the 'selectedEmployee'.
var me = new Employee ({ ID: 1, Name: 'Aaron'});
function vm() {
var self = this;
self.Project = ko.observable(new Project({ Name:'Knockout', Employee:me}));
self.selectedEmployee = ko.observable(self.Project().Employee);
self.employees = ko.observableArray([
new Employee ({ID: 1,Name: 'Aaron'}),
new Employee ({ID: 2,Name: 'George'}),
new Employee ({ID: 3,Name: 'Ross'})
]);
}
ko.applyBindings(vm);
I have a drop down list which holds a list of employees:
<select data-bind="options: employees, optionsText: 'Name',value: selectedEmployee, optionsCaption:'Pick Employee'"></select>
My Problem: The drop down list does not have an employee selected. I'm guessing this is because the 'selectedEmployee' object and the Project.Employee object are not the same.
This example works:
var me = new Employee ({ ID: 1, Name: 'Aaron'});
function vm() {
var self = this;
self.Project = ko.observable(new Project({ Name:'Knockout', Employee:me}));
self.selectedEmployee = ko.observable(self.Project().Employee);
self.employees = ko.observableArray([
me,
new Employee ({ID: 2,Name: 'George'}),
new Employee ({ID: 3,Name: 'Ross'})
]);
}
ko.applyBindings(vm);
So, what is the best practice of making the 'Employee' on the project match what is in the drop down list? Do I need to retrieve the Employee object from the list of 'employees' (based on ID) when I load it up?
I tried using an observable property for the EmployeeName (to use when displaying the value [read-only]) and EmployeeID (to use when selecting from the list), but the EmployeeName is not updated.
Seems like there should be an easy way to do this, but like I said, this is my first Knockout project.
Here's my fiddle
Thank you in advance.