JSFiddle - React, Tailwind, and code Playground

by tomm1e

HTML

<script src="https://unpkg.com/knockout@3.5.1/build/output/knockout-latest.js"></script>
<div id="model">
	<button data-bind="click: addrandom">Add Random Item</button>
	<button data-bind="click: viewitems">View items</button>
	<button data-bind="click: viewother">View other items</button>
	<br><br>
	Items: <span data-bind="text: items().length"></span>
	Other Items: <span data-bind="text: other_items().length"></span>
	<br><br>
	<div data-bind="foreach: { data: current_items(), as: 'item' }">
		<div data-bind="attr: { id: 'item-' + item.name() }">
			<button data-bind="text: item.name"></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 = {
	addrandom() {
		let c = {
			name: ko.observable(Math.random()),
		};
		this.items.push(c);
		//log("item count: " + items().length);
	},
	add(name) {
		let c = {
			name: ko.observable(name),
		};
		this.items.push(c);
		/* log("item count: " + items().length) */;
	},
	add_other(name) {
		let c = {
			name: ko.observable(name),
		};
		this.other_items.push(c);
		/* log("other item count: " + other_items().length) */;	
	},
	
	viewitems() {
		this.current_items(this.items);
	},
	
	viewother() {
		this.current_items(this.other_items);
	},
	
	items:ko.observableArray(),
	other_items:ko.observableArray(),
	
	temp:ko.observableArray(),
	/*current_items:ko.computed({
	    		read: function() { return this.temp; },
	    		write: function(a) { this.temp(a); }
	}, this),*/
	current_items:ko.observableArray()
}

ko.applyBindings(model);

model.viewitems();

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");