JSFiddle - React, Tailwind, and code Playground
by rjzaworski
HTML
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<form>
<p>Let's play a game:</p>
<div class="puzzle"></div>
<input type="submit">
</form>
CSS
body {
margin:20px;
}
JavaScript
/**
* JFF Saturdays Present: a simple capthiha with Backbone.js
* http://blog.rjzaworski.com/2012/04/a-monkey-puzzle-pattern/
*/
Puzzle = Backbone.Model.extend({
defaults: {
challenge: '',
computedSolution: 0,
proposedSolution: -1
},
order: function(arr) {
return arr.sort(function(a, b) { return b - a; });
},
random: function (max) {
return Math.floor(Math.random() * max);
},
initialize: function () {
var operator = [' + ',' - '][this.random(2)],
nums = this.order([this.random(10) + 5, this.random(10) + 1]);
var challenge = nums[0] + operator + nums[1];
this.set({
challenge: challenge + ' = ?',
computedSolution: eval(challenge)
});
},
test: function() {
if (this.get('computedSolution') != this.get('proposedSolution')) {
return 'Please complete the puzzle.';
}
}
});
/**
* View showing a puzzle
*/
PuzzleView = Backbone.View.extend({
events: {
'blur input' : 'proposeSolution'
},
tagName: 'span',
render: function() {
this.$el.empty().append(this.template(this.model.toJSON()));
return this;
},
template: _.template([
'<label class="puzzle" for="puzzle"><%= challenge %></label>',
'<input type="hidden" name="puzzleSolution" value="<%= computedSolution %>" />',
'<input type="text" name="puzzleProposed" id="puzzle" />'
].join('')),
proposeSolution: function () {
var val = this.$('input#puzzle').val();
this.model.set({ proposedSolution: val });
}
});
/**
* Run it
*/
(function() {
var puzzle = new PuzzleView({model: new Puzzle});
var result = '';
puzzle.render().$el.appendTo('.puzzle');
$('form').submit(function(e) {
e.preventDefault();
if (!(result = puzzle.model.test())) {
result = 'You passed!';
...