Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockoutjs: cascade write to multiple observables if no value yet?

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.

like image 996
BenjiFB Avatar asked Dec 14 '25 08:12

BenjiFB


1 Answers

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/

like image 175
PW Kad Avatar answered Dec 16 '25 07:12

PW Kad