Intro to Crafty - Crafty + Backbone
Eighth code demo slide from a crafty js presentation: https://github.com/ajacksified/Craftyjs-Presentation
HTML
<script src="https://raw.github.com/louisstow/Crafty/bcb8e2e9e5cd3c3dc63eab9e7ecc80e6b0b5fd9a/crafty-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.1.7/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.5.1/backbone-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.0.6/modernizr.min.js"></script>
<h1>Demo 8: Crafty + Backbone</h1>
<p>Points: <span id="points">0</span></p>
<div id="cr-stage"></div>
JavaScript
window.Game = Backbone.Model.extend({
defaults: {
'width': 600,
'height': 400,
'points': 0
},
initialize: function() {
this.coins = new CoinCollection();
coins = this.coins;
for (var x = 0; x < 25; x++) {
var xPos = Math.random() * (this.get('width') - 20) >> 0;
var yPos = Math.random() * (this.get('height') - 20) >> 0;
coins.add(new Coin({
x: xPos,
y: yPos
}));
}
this.player = new Player();
},
collectCoin: function() {
var points = this.get('points') + 1;
this.set({
points: points
});
this.trigger('change:points');
}
});
window.Player = Backbone.Model.extend({
defaults: {
'x': 10,
'y': 10
}
});
window.Coin = Backbone.Model.extend({
defaults: {
'x': 0,
'y': 0
}
});
window.CoinCollection = Backbone.Collection.extend({
model: Coin
});
window.GameView = Backbone.View.extend({
className: 'Game',
initialize: function() {
_.bindAll(this, 'render');
this.model.bind('change:points', this.updatePoints);
},
render: function() {
Crafty.init(this.model.get('width'), this.model.get('height'));
var that = this;
_.each(this.model.coins.models, function(coin) {
that.renderCoin(coin)
});
var playerView = new PlayerView({
model: this.model.player
});
},
renderCoin: function(coin) {
var coinView = new CoinView({
model: coin
});
coinView.render();
},
updatePoints: function() {
$('#points').text(this.get('points'));
}
});
window.CoinView = Backbone.View.extend({
className: 'Coin',
initialize: function() {
_.bindAll(this, 'render');
this._craftyEntity = Crafty.e('Coin');
},
render: function() {
...