knockout - dependent object attributes when managing an array
-
20-12-2019 - |
Question
I have a view model which is basically an array of objects. The object has a StartDate and an EndDate attribute. I am trying to implement a functionality wherein the EndDate of the previous item in the array should be T - 1 of the StartDate of the current item. For eg:
If the array is something like:
Type Start Date End Date
ObjectA 5/1/2014 5/31/2014
ObjectB 6/1/2014
Now, when the user changes the ObjectB's StartDate to lets say 6/15/2014, ObjectA's EndDate should automatically change to 6/14/2014.
How can I achieve this with knockout? Please help.
Solution
ObjectB start date should be observable. Then subscribe to observable property and when it changes, change property of ObjectA.
function addDays(date, value) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + value, date.getHours(), date.getMinutes(), date.getMilliseconds());
}
ObjectB.StartDate.subscribe(function (newDate){
ObjectB.EndDate(addDays(newDate, -1));
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow