Backbone.js MVC
HTML
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>
<h1>Backbone/Underscore: Game Library Test Case</h1>
<ul id=holder></ul>
<script type="text/html" id=game-template>
<li>{ name }</li>
<!-- I want to put in the ID like so:
<li>ID. Game Name</li>
But I get 'Uncaught ReferenceError: id is not defined' -->
</script>
CSS
body {
font-family: Helvetica, Arial;
}
JavaScript
var game_library;
(function($) {
_.templateSettings = {
interpolate: /\{(.+?)\}/g
};
var GameModel = Backbone.Model.extend({
url: '/gh/gist/response.json/2895708/',
name: undefined,
initialize: function() {
// Create a view for this model
this.view = new GameView({model: this});
// Sync model with server
this.save();
// Bind events
this.on('sync', this.refresh, this);
this.on('all', this.console);
},
refresh: function(model) {
console.log('sync fired ' + model.id);
model.view.render();
},
console: function(event, model, changes) {
console.log('['+ ++this.i +']-------------(event[:attr], model, changes)----------------');
console.log(event);
console.log(model);
console.log(changes);
},
i: 0
});
var GameCollection = Backbone.Collection.extend({
model: GameModel
});
var GameView = Backbone.View.extend({
el: $('#holder'),
template: $('#game-template').html(),
render: function() {
var template = _.template(this.template);
console.log(this.model.id);
this.$el.html(template(this.model.toJSON()));
}
});
// Instantiate new game collection
game_library = new GameCollection;
// Add a game
// Note: can only pass in 1 ID from gist, so only add 1 game.
var games = [
new GameModel({name: 'Skyrim'})
];
// Note: `game_library.add(new GameModel({name: 'Skyrim'}));` does
// not work for some reason having to do with instances...
game_library.add(games);
// 2 sec later...
window.setTimeout(function() {
game_library.get(1).save('name', 'The Elder Scrolls V: Skyrim');
}, 5000);
})( jQuery );