简体   繁体   中英

Can Knockout.js change variable which is not in the viewModel

This is my sample code HTML:

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

And in JavaScript I want something like.

var a = 5; 
a = ko.observable(a);

But i want to keep a number. And when i change a the input to change and when I change the input a to change.

ViewModel->Scope is possible, but Scope->ViewModel is not possible:

 var nonObservable = 5,
     observable = ko.observable(nonObservable);

// ViewModel->Scope
observable.subscribe(function(newValue) {
    nonObservable = newValue;
});

// Scope->ViewModel
observable("new value");

// This however, will not work
nonObservable = "not in any way connected";

The reason for this is that there is no way for knockout to detect what name you are binding it to ( ko.observable just knows that it has been given the value 5 , not that it has been given the name nonObservable ) ... and even if it could detect this, you would probably not want to do this by default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM