Поменяйте наблюдаемое на другое на html динамически - PullRequest
0 голосов
/ 27 сентября 2019

Поэтому я пытаюсь обновить наблюдаемое в html, изменив видимость, я думал, что это должно обновить привязку, но не происходит, есть ли другой способ обновить привязку?

// 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, но после нажатия кнопки «Изменить», счетчик должен измениться, чтобы отобразить значение счетчика 1, Iсчитал, что изменение видимости должно привести к повторной визуализации DOM и привязке к значению counter1, но оно остается с привязкой counter0.

1 Ответ

0 голосов
/ 28 сентября 2019

Привязка видимости не влияет на сами привязки, она только изменяет состояние отображения элемента DOM.Изменение связывания может быть достигнуто с помощью ko.cleanNode(DOMElement), но его следует использовать только в том случае, если вам действительно нужно полностью перестроить связывание, что не имеет место в 99 раз из 100.

В вашем случае проще создатьнаблюдаемая, которая хранит индекс активного счетчика и вычисленная, которая отображает значение активного счетчика.Смотрите код ниже.

// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
	const self = this;
	self.activeCounterIndex = ko.observable('0');
	self.counter0 = ko.observable(0);
	self.counter1 = ko.observable(0);

	this.activeCounterValue = ko.computed(function(){
		return self['counter'+self.activeCounterIndex()]();
	});

	this.add = function() {
		const newValue = self['counter'+self.activeCounterIndex()]() + 1;
		self['counter'+self.activeCounterIndex()](newValue);
	};

	this.changeCounter = () => {
		if (self.activeCounterIndex() === '0') {
			self.activeCounterIndex('1');
		} else {
			self.activeCounterIndex('0');
		}
	}
}

// Activates knockout.js
ko.applyBindings(new AppViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<p>Active counter (#<span data-bind="text:activeCounterIndex"></span>): <b data-bind="text: activeCounterValue"></b></p>
<button data-bind="click: add">Increment active counter</button>
<button data-bind="click: changeCounter">Swich counter</button>

<p>Counter #0: <span data-bind="text: counter0"></span></p>
<p>Counter #1: <span data-bind="text: counter1"></span></p>
...