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(1)">View items</button>
<button data-bind="click: => switch_view(2)">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>
View: <span data-bind="text: view"></span>
<br><br>
<div data-bind="foreach: { data: current_items, as: 'item' }">
<div>
<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 VM = function() {
this.items = ko.observableArray(),
this.add = function(name) {
let c = {
name: ko.observable(name || Math.random()),
};
this.items.push(c);
};
this.other_items = ko.observableArray();
this.add_other = function(name) {
let c = {
name: ko.observable(name || Math.random()),
};
this.other_items.push(c);
};
this.view = ko.observable(1);
this.current_items = ko.computed(() => {
if (this.view() == 1) {
console.log("returning items...");
return this.items();
} else {
console.log("returning other items...");
return this.other_items();
}
}, this);
this.switch_view = function (type) {
/* if (type == "items") {
this.current_items(this.items); // tried without () doesn't work
} else {
this.current_items(this.other_items);
} */
this.view(type);
console.log("switched to: ", this.view());
}
}
var model = new VM();
ko.applyBindings(model);
model.switch_view(1);
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");