Same data-bind value for two observable in knockoutjs

277 views Asked by At

This is my HTML Code:

<textarea name="Question" id="Question" data-bind="value:questionObj.questionText></textarea>

And this is my JavaScript Code:

questionObj = {
       questionText: ko.observable(' '),
       title:  ko.observable(' ')
};

questionText is data-binded to the textarea and the value is observable in bothway.I want questionObj.title to get the same value inside the questionObj.questionText. Is there any way to bind likewise ?

3

There are 3 answers

1
Ray On BEST ANSWER

You mean you want both observables to have the same value? You can use a pureComputed observable for that.

Change your observable definition like this:

questionObj = {
   questionText: ko.observable(' ')
};

questionObj.title = ko.pureComputed(function(){
    return questionObj.questionText();
}, questionObj);
2
Iam_NSA On

This solved my issue....

   questionObj = {
           questionText: ko.observable(' '),
           title:  ko.observable(' ')
    };

    questionObj.title(questionObj.questionText);
0
MKougiouris On

@Iam_NSA response:

Hey there. While you might have gotten the functionality that you were looking for it is worth noting that what you have done is 2 observables and then you assign the reference to one of the observables it self, not its value, to the other one. Unless you do it intentionally, which you do not, otherwise you would not be here asking around :P, you should avoid it. Essentialy you only have one observable as you stand, which would be equal to just binding the same observable to 2 different elements.

You are better of creating a pure computed OR a subscription like so :

questionObj = {
           questionText: ko.observable(' '),
           title:  ko.observable(' ')
    };

    questionObj.questionText.subscribe(function(val){
        questionObj.title(val);
    });