Backbone List with Sub-View
Backbone List with Sub-View
by Nirvanachain
HTML
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>
<script type="text/template" id="listContainer">
<h3>Stat = <%- collection[0].stat %></h3>
<ul>
</ul>
</script>
<script type="text/template" id="item">
<% console.log(collection) %>
<% _.each(collection[0].photos.photo, function(element, index) { %>
<li><%- element.title %></li>
<% }); %>
</script>
<div class="js-container">
</div>
JavaScript
var TheModel = Backbone.Model.extend({
default: {
photos: '',
stat: ''
}
});
var TheCollection = Backbone.Collection.extend({
model: TheModel,
url: 'http://api.flickr.com/services/rest/?page=1&api_key=a2978e5ce30c337e3b639172d3e1a0d1&tags=candy&method=flickr.photos.search&per_page=3&format=json&jsoncallback=?'
});
// The main view
var List = Backbone.View.extend({
el: '.js-container',
initialize: function () {
var self = this;
this.collection = new TheCollection();
this.item = new ListItem({collection: this.collection});
return this;
},
render: function () {
var self = this;
this.collection.fetch({
dataType: 'jsonp',
success: function (data) {
var listTemplate = _.template( $('#listContainer').html(), {
collection: self.collection.toJSON()
});
self.$el.html(listTemplate);
//self.$el.html( self.item.render() );
//console.log(self.$('ul'));
self.$('ul').append( self.item.render() );
}
});
return this;
}
});
var ListItem = Backbone.View.extend({
render: function () {
var itemTemplate = _.template( $('#item').html(), {collection: this.collection.toJSON()} );
return itemTemplate;
}
});
var myList= new List();
myList.render();