Backbone Without Flat JSON
Backbone Without Flat JSON
HTML
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>
<div class="js-container">
</div>
<script type="text/template" id="item-template">
<p>
<%= title %>
<%= color %>
<% _.each(type, function(ele, i) { %>
<%- ele.isStandard %>,
<%- ele.size %>,
<% }); %>
<%= price %>
</p>
</script>
<script type="text/template" id="some-template">
<h3>How should I get the 'page', 'total', and 'date' properties in the data here?</h3>
<div class="items"></div>
</script>
JavaScript
var Item = Backbone.Model.extend({
defaults: {
"title": "no-title",
"color": "no",
"type": [],
"price": "0"
}
});
var ItemsCollection = Backbone.Collection.extend({
model: Item
});
var PageModel = Backbone.Model.extend({
defaults: {
page: 0,
date: 'now',
total: 0,
items: []
},
parse: function(resp) {
this.set('items', new ItemsCollection(resp[0].items));
},
url: 'https://api.mongolab.com/api/1/databases/backbonecollectiontest/collections/backbonecollection?apiKey=qcVNgNb-s1X4WJkLeRDfykxqtMG-ezkC',
});
var ItemView = Backbone.View.extend({
template: _.template( $('#item-template').html() ),
render: function() {
this.$el.html( this.template(this.model.toJSON()));
return this;
}
});
var ItemsView = Backbone.View.extend({
render: function(){
this.collection.each(function(item){
var itemView = new ItemView({ model: item });
console.log(itemView.render())
this.$el.append(itemView.render().el);
}, this);
return this;
}
});
var TheView = Backbone.View.extend({
el: '.js-container',
initialize: function() {
this.model = new PageModel();
this.model.fetch();
this.listenTo(this.model, 'sync', this.render);
},
template: _.template( $('#some-template').html() ),
render: function() {
console.log( 'PageModel =',this.model.toJSON() );
this.$el.html( this.template( {model: this.model.toJSON()} ) );
var itemsColl = this.model.get('items');
var itemsView = new ItemsView({
el: '.items',
collection: itemsColl
});
itemsView.render();
}
});
var theView = new TheView();