【发布时间】:2020-01-28 02:50:00
【问题描述】:
我正在尝试通过更改可见性来更新 html 上的 observable,我认为它应该更新绑定但没有发生,是否有另一种方法来更新绑定?
// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
this.isVisible = ko.observable(true);
this.counter0 = ko.observable(0);
this.counter1 = ko.observable(0);
this.counterDisplay = this.counter0;
this.add = function() {
console.log(this.counterDisplay());
const newValue = this.counterDisplay() + 1;
this.counterDisplay(newValue);
};
this.changeCounter = () => {
this.isVisible(!this.isVisible());
if(this.counterDisplay === this.counter0) {
this.counterDisplay = this.counter1;
console.log('change to counter1');
} else {
this.counterDisplay = this.counter0;
console.log('change to counter0');
}
this.isVisible(true);
}
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<p>Counter Main: <div data-bind="text: counterDisplay, visible: isVisible"></div></p>
<button data-bind="click: add">Add</button>
<button data-bind="click: changeCounter">Change</button>
<p>Counter0: <div data-bind="text: counter0"></div></p>
<p>Counter1: <div data-bind="text: counter1"></div></p>
在示例中,主计数器显示计数器 0 的值,但单击更改按钮后主计数器应更改为显示 counter1 值,我认为更改可见性应重新渲染 DOM 并绑定到counter1 的值,但它仍然与 counter0 绑定。
【问题讨论】:
标签: html data-binding knockout.js