JSFiddle - React, Tailwind, and code Playground
by alego ra
HTML
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script src="https://shelme.com/js/underscore.js"></script>
<script src="https://shelme.com/js/backbone.js"></script>
<p><a href="javascript:void(0)" onclick="location.reload();">refresh page</a> <--- click me</p>
<h1>Menu</h1>
<ul class="menu">
<li><a href="#!/">main</a></li>
<li><a href="#!/order/1">Order 1</a></li>
<li><a href="#!/order/2">Order 2</a></li>
<li><a href="#!/order/3">Order 3</a></li>
</ul>
<h1>Content</h1>
<div id="block"></div>
<script type="text/template" id="main">
<div id="mainContent"></div>
</script>
<script type="text/template" id="order">
<div id="orderContent"></div>
</script>
CSS
.menu{display:block;margin-bottom:20px;paddding:20px;border:1px solid #cccccc;}
JavaScript
$(function () {
var AppState = Backbone.Model.extend({
defaults: {
state: "main"
}
});
var appState = new AppState();
var Controller = Backbone.Router.extend({
routes: {
"": "main",
"!/": "main",
"!/order": "order",
"!/order/:id": "order",
},
main: function () {
appState.set({ state: "main" });
$('#mainContent').html('main content');
},
order: function (id) {
appState.set({ state: "order" });
$('#orderContent').html(id);
}
});
var controller = new Controller();
var Block = Backbone.View.extend({
el: $("#block"),
templates: {
"main": _.template($('#main').html()),
"order": _.template($('#order').html()),
},
initialize: function () {
this.model.bind('change', this.render, this);
},
render: function () {
var state = this.model.get("state");
$(this.el).html(this.templates[state](this.model.toJSON()));
return this;
}
});
var block = new Block({ model: appState });
appState.trigger("change");
appState.bind("change:state", function () {
var state = this.get("state");
if (state == "main")
controller.navigate("!/", false);
else
controller.navigate("!/" + state, false);
});
Backbone.history.start();
});