I've got a form where I plan to collect info for multiple people. There's a high likelihood that the responses may be identical for each person, but I want to give people the ability to give customized responses while still keeping it simple. So, I put together an example:
http://jsfiddle.net/r29xtLaq/1/
It's a really simple input form:
<p>Person 1: <input data-bind='value: person1' /></p>
<p>Person 2: <input data-bind='value: person2' /></p>
In this jsfiddle, I would like it to be so that when I fill in a value for person1, that value will automatically be cascaded to person2 at the beginning, since the value for person2 is empty. But they are both backed by separate observables because after prefilling person2 for the user, she or he can edit person2, and it will not cascade back to person1.
Have you tried anything to accomplish this yet? This should be fairly simple by implementing a custom extender in Knockout which subscribes to value changes and checks for others to be empty and fills them in.
Ex. extender -
ko.extenders.setOthersOnChange = function(target, others) {
target.subscribe(function(newValue) {
ko.utils.arrayForEach(others, function (other) {
if (!ko.unwrap(other)) {
other(newValue);
}
});
});
return target;
};
And in your VM -
this.person2 = ko.observable().extend({ setOthersOnChange: [] });
this.person1 = ko.observable().extend({ setOthersOnChange: [this.person2] });
The benefit here is you can have n number of other dependent observables without increasing how many subscriptions you have to manually create. I would also suggest ensuring you dispose of them properly.
Updated fiddle for reference
http://jsfiddle.net/r29xtLaq/3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With