Ray Cheng
Ray Cheng

Reputation: 12566

How to bind one html element to two observables?

I know how to bind one observable to two html elements, but how can I bind one html element to two observables with two way binding?

The html element is an input textbox.

Upvotes: 1

Views: 1393

Answers (3)

Michael Best
Michael Best

Reputation: 16688

You ask about binding a single input field to two observables, but if your model dictates that the two observables should always be equal, that logic should be in your model, independent of your view and bindings.

To have two always equal observables, you can make one a plain observable and the other a computed observable which just reads and updates the first one.

function ViewModel() {
    this.first = ko.observable();
    this.second = ko.computed({
        read: this.first,
        write: this.first
    });
}

Then your input can be bound to either one.

EDIT: If your two properties are really just synonyms of each other, you can assign the same observable to both. This takes advantage of observables being actual objects.

function ViewModel() {
    this.second = this.first = ko.observable();
}

Upvotes: 2

PW Kad
PW Kad

Reputation: 14995

The simplest way to achieve this is to not actually bind both to the same HTML element, but to subscribe to the changes of one observable, setting the value of another... If that makes sense...

In the view -

<div>
    <input data-bind="value: myFirstObs" />
    <span data-bind="text: myFirstObs" />
    <span data-bind="text: mySecondObs" />
</div>

and in the view model -

var myFirstObs = ko.observable();
var mySecondObs = ko.observable();

myFirstObs.subscribe(function () {
    mySecondObs(myFirstObs());
}

Your question is definitely a unique one...

Upvotes: 3

Damien
Damien

Reputation: 8987

I would do that :

The view

 <input type="text" data-bind="value: firstname" />

The viewmodel :

var  vm = {
    firstname : ko.observable(),
    firstnameCopy = ko.computed({
        read : function() {return this.firstname();},
        write : function(value) { this.firstname(value);},
        owner : this
    })
};

Upvotes: 1

Related Questions