簡體   English   中英

Knockout.js是否可以更改不在viewModel中的變量

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

這是我的示例代碼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";

這樣做的原因是,敲除沒有辦法檢測到您將其綁定到的名稱( ko.observable只是知道它的值是5 ,而不是它的名稱是nonObservable )...並且即使它可以檢測到此問題,您也可能默認情況下不希望這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM