这是我的示例代码 HTML:
<input type="text" data-bind="value: a"/>
在 JavaScript 中我想要类似的东西。
var a = 5;
a = ko.observable(a);
但我想保留一个号码。当我将输入更改为更改时,当我将输入更改为更改时。
最佳答案
ViewModel->Scope
是可能的,但是 Scope->ViewModel
不是可能的:
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";
这样做的原因是,knockout 无法检测您将其绑定(bind)到什么名称(ko.observable
只知道它已被赋予值 5
,并不是说它已被命名为 nonObservable
) ... 即使它可以检测到这一点,您也可能不想默认执行此操作。
关于javascript - Knockout.js 可以更改不在 viewModel 中的变量吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21147144/