JSFiddle - React, Tailwind, and code Playground
by knunery
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js"></script>
<div id="click_container" class='liveExample'>
</div>
<script type="text/template" id="click_template">
<div>You've clicked <span><%= numberOfClicks %></span> times</div>
<% if( !hasClickedTooManyTimes ) {%>
<button name="click_me">Click me</button>
<%}%>
<% if( hasClickedTooManyTimes ) {%>
<div class="clickMessage reset">
That's too many clicks! Please stop before you wear out your fingers.
<button name="reset">Reset clicks</button>
</div>
<%}%>
</script>
CSS
body { font-family: arial; font-size: 14px; }
.liveExample { padding: 1em; background-color: #EEEEDD; border: 1px solid #CCC; max-width: 655px; }
.liveExample input { font-family: Arial; }
.liveExample b { font-weight: bold; }
.liveExample p { margin-top: 0.9em; margin-bottom: 0.9em; }
.liveExample select[multiple] { width: 100%; height: 8em; }
.liveExample h2 { margin-top: 0.4em; }
JavaScript
var ClickModel = Backbone.Model.extend({
defaults: {
numberOfClicks: 0,
MAX_CLICKS: 3,
hasClickedTooManyTimes: false
},
updateModel: function() {
if (this.get('numberOfClicks') > this.get('MAX_CLICKS')) {
this.set('hasClickedTooManyTimes', true);
}
}
});
var ClickView = Backbone.View.extend({
template: _.template($('#click_template').html()),
render: function() {
this.$el.html(this.template(this.model.toJSON()));
},
events: {
"click button[name='click_me']": function() {
var clicks = this.model.get('numberOfClicks') + 1;
this.model.set({
"numberOfClicks": clicks
});
this.model.updateModel();
this.render();
},
"click button[name='reset']": function(){
this.model = new ClickModel();
this.render();
}
}
});
var clickModel = new ClickModel({});
var clickView = new ClickView({
model: clickModel
});
clickView.render();
$("#click_container").html(clickView.el);
/*
var clickCounterViewModel = function() {
this.numberOfClicks = ko.observable(0);
this.registerClick = function() {
this.numberOfClicks(this.numberOfClicks() + 1);
}
this.hasClickedTooManyTimes = ko.dependentObservable(function() {
return this.numberOfClicks() >= 3;
}, this);
};
ko.applyBindings(new clickCounterViewModel());
*/