Backbone.js ZombieS!
by Gary Kaganas
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone.js"></script>
<h3> Creates and tests Backbone Zombie views using a Router</h3>
<p>Click on New View to create your first view. After that clear the route (by clicking Clear Route) and create another view isntance identical to the first. Repeat to create multiple zombie views</p>
<a id="new-view" href="#/new" class="btn btn-warning">New View</a>
<a id="switch-view" href="#/switch" class="btn btn-primary">Clear Route</a>
<hr/>
<label>Zombie Counter:</label>
<input id="counter" name="counter" size="3" value="0">
<hr/>
<div id="view-el"></div>
<script type="text/template" id="zombie-template">
<p> After you 've created multiple views, click on the Zombied event. It'
s simpy wired with the view 's <code>events</code> hash.</p>
<a class="btn btn-primary" id="zombie" href="#/new">Zombied Event</a>
<a class="btn btn-primary" id="kill-zombie" href="#/new">Kill All Zombies</a>
</script>
CSS
body {
padding: 10px;
}
#view-el {
border: 1px solid orange;
}
JavaScript
var App = [];
var Router = Backbone.Router.extend({
routes: {
'new': 'newView'
},
newView: function (id) {
debugger;
var aview = new AView();
aview.render();
$("#switch-view").toggleClass("btn-primary btn-warning");
$("#new-view").toggleClass("btn-primary btn-warning");
}
});
var AView = Backbone.View.extend({
el: "#view-el",
initialize: function () {
App.push(this);
$("#counter").val(App.length);
},
events: {
'click #zombie': 'seeTheLight',
'click #kill-zombie': 'killAZombie'
},
seeTheLight: function () {
debugger;
$("</p>").text("I am Zombie").appendTo(this.$el);
console.log("I am Zombie");
},
killAZombie: function() {
this.remove();
},
render: function () {
this.$el.html(_.template($('#zombie-template').html()));
},
});
var router = new Router();
Backbone.history.start();
$("#switch-view").click(function () {
$(this).toggleClass("btn-primary btn-warning");
$("#new-view").toggleClass("btn-primary btn-warning");
});