JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.0/backbone.js"></script>
<script type="text/template" id='bottles_template'>
<p class="bottles"><%= bottles %> bottles of beer on the wall</p>
<button class="take">Take one down and pass it around</button>
<button class="again">Start again</button>
</script>
<div id="container"></div>
JavaScript
var BottleGameView = Backbone.View.extend({
el: '#container',
events: {
'click button.take': 'takeBottle',
'click button.again': 'startAgain'
},
initialize: function () {
this.model = new Backbone.Model({ bottles: 99 });
this.render();
this.listenTo(this.model, 'change:bottles', this.handleBottlesChange);
},
handleBottlesChange: function () {
var bottles = this.model.get('bottles');
if (bottles > 0) {
this.$take.show();
this.$again.hide();
} else {
this.$take.hide();
this.$again.show();
}
if (bottles > 1) {
this.$para.text(bottles + ' bottles of beer on the wall');
} else if (bottles === 1) {
this.$para.text('One bottle of beer on the wall');
} else {
this.$para.text('No bottles of beer on the wall');
}
},
render: function () {
var template = _.template($('#bottles_template').html(), this.model.attributes);
this.$el.html(template);
this.$para = this.$el.find('.bottles');
this.$take = this.$el.find('.take');
this.$again = this.$el.find('.again');
this.$again.hide();
},
takeBottle: function () {
this.model.set('bottles', this.model.get('bottles') - 1);
},
startAgain: function () {
this.model.set('bottles', 99);
}
});
new BottleGameView();