I'm new to Knockout.js and am trying to create a complex object based on a work history.
I'm currently able to pass in the data An employee has positions which have projects which have experiences, etc etc. While I'm able to pass in the data and populate the child objects, I believe what want to do is build up my child objects manually so I can attach methods and computedObservables. I'm just not sure how do wire up my other objects. Do I write a for each loop or is there some spiffy knockout magic to make this simpler?
any guidance would be greatly appreciated!
Namespace.viewModel = function (model) {
console.log('initViewCalled');
var memberVM = {
Id: ko.observable(model.Id),
FName: ko.observable(model.FName),
LName: ko.observable(model.LName),
Positions: ko.observableArray(model.Positions),
};
// computed goodness goes here
memberVM.FullName = ko.computed(function () {
return this.FName() + ' ' + this.LName();
}, memberVM);// methods
this.addPosition = function () {
this.Positions.push({MemberId:this.MemberId });
} .bind(this);
return memberVM;
};
Namespace.position = function (model) {
var positionVM = {
EndDate: ko.observable(model.EndDate),
Description: ko.observable(model.Description),
HoursPerWeek: ko.observable(model.HoursPerWeek),
HourlyRate: ko.observable(model.HourlyRate),
MaxDate: ko.observable(model.MaxDate),
MinDate: ko.observable(model.MinDate),
MemberId: ko.observable(model.Id),
Name: ko.observable(model.Name),
PositionId: ko.observable(model.Id),
Summary: ko.observable(model.Summary),
SalaryEnd: ko.observable(model.SalaryEnd),
SalaryStart: ko.observable(model.SalaryStart),
StartDate: ko.observable(model.StartDate),
Title: ko.observable(model.Title),
Projects: ko.observableArray(model.Projects), // automapped...
};
this.addProject = function () {
this.Projects.push({ MemberId: this.MemberId });
} .bind(this);
return positionVM;
};
Namespace.project = function(model) {
var projectVM = {
EndDate: ko.observable(model.EndDate),
Description: ko.observable(model.Description),
MemberId: ko.observable(model.Id),
Name: ko.observable(model.Name),
PositionId: ko.observable(model.Id),
StartDate: ko.observable(model.StartDate),
Experiences: ko.observableArray(model.Experiences) // auto-mapped
};
this.addExperience = function () {
this.Experiences.push("New Experience");
}.bind(this);
return projectVM;
};