Backbone Test
Backbone Test
by Nirvanachain
HTML
<script src="http://underscorejs.org/underscore.js"></script>
<script src="http://backbonejs.org/backbone.js"></script>
<script type="text/template" id="itemContainerTemplate">
<p>hi</p>
<ul>
</ul>
<p>bye</p>
</script>
<script type="text/template" id="itemTemplate">
<% _.each(model, function (value, key) { %>
<li><%= key %> is <%= value %></li>
<% }); %>
</script>
<div class="js-container">
</div>
JavaScript
var ItemModel = Backbone.Model.extend({
defaults: {
name: 'Guest User',
age: 23,
occupation: 'worker'
}
});
var itemData = new ItemModel();
var Item = Backbone.View.extend({
el: 'ul',
myTemplate: function (data) {
var temp = _.template( $('#itemTemplate').html(), {model: data} );
this.$el.html(temp);
return this;
},
initialize: function () {
this.render();
},
render: function () {
this.myTemplate(this.model.toJSON() );
return this;
}
});
var ItemContainer = Backbone.View.extend({
el: '.js-container',
myTemplate: function (data) {
var temp = _.template( $('#itemContainerTemplate').html(), {model: data} );
this.$el.html(temp);
return this;
},
initialize: function () {
this.render();
new Item({model:itemData});
return this;
},
render: function () {
this.myTemplate(this.model.toJSON() );
return this;
}
});
var itemContainer = new ItemContainer({model:itemData});