Reputation: 5440
I'm trying to build a simple 2D game while learning Backbone, and I'm having difficulties with how inheritance works. Why isn't the default values in EntityModel set? The output from tick() is always:
x: undefined
y: undefined
Simplified code:
$(function(){
EntityModel = Backbone.Model.extend({
defaults: function(){
return {
x : 0,
y : 0
};
},
tick: function(){
console.log('x: ' + this.get('x'));
console.log('y: ' + this.get('y'));
}
});
PlayerModel = EntityModel.extend({
defaults: function() {
return {
name : 'John Doe',
health : 10
};
},
initialize: function(options){
console.log('New player ('+this.get('name')+') entered the game');
}
});
var player1 = new PlayerModel();
var gameloop = window.setInterval(function(){
player1.tick();
}, 40);
});
Upvotes: 1
Views: 87
Reputation: 33344
The defaults
declaration in PlayerModel
masks the declaration done in its parent class. You have to explicitly incorporate the defaults from EntityModel
. For example :
var PlayerModel = EntityModel.extend({
defaults: function() {
var defaults_parent = _.result(EntityModel.prototype, 'defaults'),
defaults_self = {
name : 'John Doe',
health : 10
};
return _.defaults(defaults_self, defaults_parent);
}
});
And a demo http://jsfiddle.net/nikoshr/epCsy/
Upvotes: 2