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

I have a form where I am going to collect information for several people. There is a high probability that the answers might be the same for every person, but I want to give people the ability to give individual answers while keeping everything simple. So I put together an example:

http://jsfiddle.net/r29xtLaq/1/

This is 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 a value for person1, that value will automatically cascade for person2 at the beginning, since the value for person2 is empty. But they are both backed up by separate observables, because after pre-populating person2 for user, he or she can edit person2 and it won't go back to person1.

+3


source to share


3 answers


Have you tried anything for this? It should be pretty straightforward by implementing a custom expander in Knockout that accepts cost changes and checks to make sure others are empty and fill them.

Ex. expander -

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] });

      

You can get the n

number of other dependent observables without increasing the number of signatures you have to manually create. I would also like to invite you to properly manage them.

Updated script for reference

http://jsfiddle.net/r29xtLaq/3/

+2


source


You can subscribe

change to person1

and put its value to person2

only if the latter is still empty:

var self = this;

this.person1.subscribe(function(val)
{
    if (!self.person2())
        self.person2(val);
});

      



See modified Fiddle

+1


source


If you want to cascade from person1 to person2, you'll love cna so much.

http://jsfiddle.net/r29xtLaq/1/

// Here my data model
var ViewModel = function(first, last) {
    var self = this; 
    self.person1 = ko.observable(first);
    self.person2 = ko.observable(last);
    self.person1.subscribe(function(newValue) {   
          if(self.person2() == '')       
          self.person2(newValue);
    });
}  
ko.applyBindings(new ViewModel("", ""));

      

+1


source







All Articles