How to have one dependency use another?
I have one property on my view model that is used in a select
element. Bound to the value of this select
is a chosenproduct.
Now I want a third propert开发者_运维知识库y to use a field on the chosenproduct, but how do I do that?
I tried something like this, with no luck:
viewModel = {
startDateAndTime: ko.observable(new Date()),
selectedProduct : products[0],
endDateAndTime : ko.observable(new Date(this.startDateAndTime).add({minutes: this.selectedProduct.duration}))
//the rest goes here
The first two properties works fine, but the third is not working.
You'll be using dependent observables for this >
viewModel = {
startDateAndTime: ko.observable(new Date()),
selectedProduct : products[0]
}
viewModel.endDateAndTime = ko.dependentObservable(function () {
return new Date(this.startDateAndTime).add({minutes: this.selectedProduct.duration}));
}, viewModel);
Important to note is that you can only add dependent observables once you have already declared the viewModel
(e.g. above we declared endDataAndTime
outside of viewModel
declaration). Steve (the author of knockoutjs) writes extensively why under the heading 'Managing this'.
精彩评论