JSFiddle - React, Tailwind, and code Playground
by kuyabiye
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-debug.js"></script>
<div id="container">
<div id="header"></div>
<div id="content"></div>
</div>
<script type="text/html" id="login">
<div class="login js-module" data-model="APP.Login">
<form data-bind="submit: login, visible: !isLoggedIn()">
<input type="text" name="username" data-bind="value: username, valueUpdate: 'afterkeydown'" />
<input type="submit" value="submit" />
</form>
<div data-bind="visible: isLoggedIn">
<span data-bind="text: username"></span> <a href="#" data-bind="click: logout">logout</a>
</div>
</div>
</script>
<script type="text/html" id="games">
<div class="games js-module" data-model="APP.Games">
<div data-bind="foreach: games">
<div><span data-bind="text: name"></span> <a href="#" data-bind="click: play">play</a></div>
</div>
</div>
</script>
<script type="text/html" id="play">
<div class="games js-module" data-model="APP.Play">
<div></div>
</div>
</script>
JavaScript
var APP = APP || {};
APP.addContent = function(page, context) {
debugger;
var $content = context ? $(context) : $("#content");
$content.html($(page).html());
APP.bindModelandView($content);
}
APP.bindModelandView = function($context) {
var module = $context.find(".js-module");
module.each(function() {
var data = this.dataset,
Model = getFunctionByName(data.model);
new Model(this, data);
});
}
APP.Login = function(view, options) {
var self = this;
this.username = ko.observable();
this.isLoggedIn = ko.observable(false);
this.login = function() {
if ( self.username() === "berkin" ) {
self.isLoggedIn(true);
APP.addContent("#games");
} else {
self.username("");
}
}
this.logout = function() {
self.isLoggedIn(false);
$("#content").html("");
}
ko.applyBindings(this, view);
}
APP.Games = function(view, options) {
this.games = ko.observableArray([new APP.Game({"name": "star"}), new APP.Game({"name": "jack"})]);
ko.applyBindings(this, view);
}
APP.Game = function(item) {
this.name = ko.observable(item.name);
this.play = function() {
APP.addContent("#play");
}
}
APP.addContent("#login", "#header");
function getFunctionByName(functionName) {
var context = window;
var namespaces = functionName.split(".");
for (var i = 0, j = namespaces.length - 1; i < j; i++) {
context = context[namespaces[i]];
if(context === undefined){
return;
}
}
var func = namespaces[namespaces.length - 1];
return context[func];
};