Skip to content

Instantly share code, notes, and snippets.

@jpetto
Last active August 29, 2015 13:58
Show Gist options
  • Save jpetto/10331995 to your computer and use it in GitHub Desktop.
Save jpetto/10331995 to your computer and use it in GitHub Desktop.
ASWM: Backbone Model/View - basic example
// make/get a reference to our namespace
var MyApp = window.MyApp || {};
// create our VideoGame model with defaults
MyApp.VideoGame = Backbone.Model.extend({
defaults: {
title: 'Coming soon...',
publisher: '',
release_year: '',
box_art: 'placeholder.jpg',
platforms: [],
description: ''
}
});
// create our VideoGame view
MyApp.VideoGameView = Backbone.View.extend({
// specify the tag that should wrap/contain the view
// this used to be in the template
tagName: 'li',
// pre-compile the template for later use
template: _.template($('#videogame-template').html()),
// event handlers for actions that take place within the template
events: {
// when a user clicks on an element inside the template with
// the 'select' class, execute the 'selectGame' function
'click .select': 'selectGame'
},
// function to toggle the 'select' class on the template's
// wrapper tag (specified above in 'tagName')
selectGame: function() {
// this.$el refers to the element of the view (<li>) referenced
// as a jQuery object
//console.log(this.el);
//console.log(this.$el);
this.$el.toggleClass('selected');
},
// function to create the new markup based on the model and template
render: function() {
// generate new html by sending the model's JSON representation
// to this view's template
var newHtml = this.template(this.model.toJSON());
// set the html of this view's wrapper element
this.$el.html(newHtml);
// used for chaining (see line 79)
return this;
}
});
// populate an object literal with model data.
// the key names must match the defaults names as specified
// in the model
var vgData = {
title: 'Double Dribble',
publisher: 'Konami',
release_year: '1986',
box_art: 'http://cdn3.spong.com/pack/d/o/doubledrib22713/_-Double-Dribble-NES-_.jpg',
description: 'Basketball game!',
platforms: ['NES', 'Genesis']
};
// create a new instance of our VideoGame model, passing in
// our object literal to populate the attributes
var vg = new MyApp.VideoGame(vgData);
// create a new instance of our VideoGameView view, passing
// in our vg instance
var vgView = new MyApp.VideoGameView({ model: vg });
// generate and store the new html based on the vgView
var vgHtml = vgView.render().el;
console.log(vgHtml);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment