Photo Backbone tut
by Sander Houttekier
HTML
<script src="https://raw.github.com/documentcloud/underscore/master/underscore.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.5.3/backbone-min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<script id="results-template" type="text/template">
<h2><%= title %></h2>
</script>
<div id="results"></div>
JavaScript
Photo = Backbone.Model.extend({
defaults: {
src: 'placeholder.jpg',
title: 'an image placeholder',
coordinates: [0,0],
tags: ['untagged'],
location: 'home'
},
initialize: function(){
this.bind('foo', this.msgTitlechanged )
.bind('bar', this.othermsgChanged);
},
othermsgChanged: function(title){
console.log("bar fired: " + title);
},
msgTitlechanged: function(title){
console.log("title was changed to " + this.get("title"));
},
setTitle: function(title){
this.set({title: title});
}
});
var PhotoSearch = Backbone.View.extend({
el: $('#results'),
initialize: function(){
var myPhoto = new Photo();
console.log('view initialized');
console.log(JSON.stringify(myPhoto));
this.render();
},
render: function(event){
var compiled_template = _.template( $("#results-template").html() );
this.el.html(compiled_template(myPhoto.toJSON()));
return this;
}
});
PhotoCollection = Backbone.Collection.extend({
model: Photo
});
/*We can then create our own instance of a photo as follows:*/
var myPhoto = new Photo();
var search = new PhotoSearch(myPhoto);