knockoutjs - 如何观察全局变量变化

knockoutjs - How to observe global variable change

我需要观察变量myGlobalVar。我需要检测对其的更改并显示它们。

function AppViewModel() {
    this.myVar = ko.observable(myGlobalVar);
}

// Activates knockout.js
ko.applyBindings(new AppViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<script>myGlobalVar = "Foo";</script>

<p>Test: <strong data-bind="text: myVar"></strong></p>

<script>
setTimeout(function() {
    myGlobalVar = "Bar";
    console.log("myVar set to 'Bar'. Proof:");
    console.log(myGlobalVar);
}, 1000);
</script>

在上面的示例代码中,我最初将 window.test 设置为“Foo”,然后在 3 秒后将其设置为“Bar”,但未检测到更改。

你可以只更新 observable 而不是全局变量,为此我给你举了一个例子,你可以如何使用 vm.myVar(value)

从任何地方改变它

如果您认为这没有帮助,请三思,您可以创建一个区间函数来设置当前全局变量,例如 vm.myVar(myGlobalVar)

这就是“可观测值”存在的原因 希望它真的有帮助 ;)

myGlobalVar = "Foo";
function AppViewModel() {
    this.myVar = ko.observable(myGlobalVar);
}

// Activates knockout.js (you see i´m assigning var vm)
var vm = new AppViewModel();
ko.applyBindings(vm);

setTimeout(function() {
    // edit the observable to update view
    vm.myVar("Bar") ;
    console.log("myVar set to 'Bar'. Proof:");
    console.log(vm.myVar());
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<script>myGlobalVar = "Foo";</script>

<p>Test: <strong data-bind="text: myVar"></strong></p>

我能够解决这个问题,谢谢“john Smith”的回答,我更改它以添加更改方法。我也可以只使用一个间隔,但在这种情况下更改更好。

myGlobalVar = "Foo";
function AppViewModel() {
    this.myVar = ko.observable(myGlobalVar);
}

// Activates knockout.js (you see i´m assigning var vm)
var vm = new AppViewModel();
ko.applyBindings(vm);

setTimeout(function() {
    // edit the observable to update view
    vm.myVar("Bar") ;
    console.log("myVar set to 'Bar'. Proof:");
    console.log(vm.myVar());
}, 1000);



$("#globalVarField").change(function() {
    myGlobalVar = $(this).val();
    console.log("globalVarField changed to '"+ myGlobalVar + "'");
    
    vm.myVar(myGlobalVar);
});
.as-console-wrapper { max-height: 100px !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<script>myGlobalVar = "Foo";</script>

<p>Test: <strong data-bind="text: myVar"></strong></p>

Enter a value for myGlobalVar: <input type="text" id="globalVarField">