JSFiddle - React, Tailwind, and code Playground

by tomm1e

HTML

<script src="https://cdn.jsdelivr.net/npm/@tko/build.reference@4.0.0-alpha8/dist/build.reference.min.js"></script>
<div id="model">
	<button data-bind="click: => add()">Add to Items</button>
	<button data-bind="click: => add_other()">Add to Other Items</button>
	<button data-bind="click: => switch_view('items')">View items</button>
	<button data-bind="click: => switch_view('other')">View other items</button>
	<br><br>
	Items: <span data-bind="text: items().length"></span><br>
	Other Items: <span data-bind="text: other_items().length"></span>
	<br><br>
	<div data-bind="foreach: { data: current_items(), as: 'item' }">
		<div>
			<button data-bind="text: item"></button>
		</div>
	</div>
</div>

<pre id="log"></pre>

CSS

#model {
	border:1px solid red;
	padding:10px;
}

JavaScript

function log(msg) {
	$("#log").append(msg + "<br>");
}
// https://cdn.jsdelivr.net/npm/@tko/build.reference@4.0.0-alpha8/dist/build.reference.min.js
// https://unpkg.com/tko@4.0.0-alpha4a/dist/tko.js
// https://unpkg.com/knockout@3.5.1/build/output/knockout-latest.js
var model = {
	items:ko.observableArray(),
	add(name) {
		let c = {
			name: ko.observable(name || Math.random()),
		};
		this.items.push(c);
		/* this.current_items.valueHasMutated(); */
	},
	
	other_items:ko.observableArray(),
	add_other(name) {
		let c = {
			name: ko.observable(name || Math.random()),
		};
		this.other_items.push(c);
		/* this.current_items.valueHasMutated(); */
	},

	current_items:ko.observableArray(),	
	
	switch_view(type) {
		if (type == "items") {
			this.current_items(this.items); // tried without () doesn't work
			/* this.current_items.valueHasMutated(); */
		} else {
			this.current_items(this.other_items);
			/* this.current_items.valueHasMutated(); */
		}
	}
}

ko.applyBindings(model);

model.switch_view("items");

model.add("item1");
model.add("item2");
model.add("item3");

model.add_other("other1");
model.add_other("other2");
model.add_other("other3");
model.add_other("other4");

model.add("item4");
model.add("item5");