Backbone Model Template
Standard fiddle
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.3/backbone-min.js"></script>
JavaScript
// Create a new view class which will render you model
var BookView = Backbone.View.extend({
// Use underscores templating
template: _.template('<strong><%= title %></strong> - <%= author %>'),
initialize: function() {
// Render the view on initialization
this.render();
// Update the view when the model is changed
this.listenTo(this.model, "change", this.render);
},
render: function() {
// Render your model data using your template
this.$el.html(this.template(this.model.toJSON()));
// Maintain chainability
return this;
}
});
// Create a model class
var Book = Backbone.Model.extend({
urlRoot: 'https://api.yotpo.com/v1/widget/4X91rXasdFWFBX4Rnh5WEr4NnvMwpFpjxzNFLubD/products/891/reviews',
defaults: {
name: '',
email: ''
},
initialize: function(){
}
});
// Some dummy data
var instance ={
title: 'learn Backbone JS',
author: 'Bobby Longsocks',
};
// Instansite your model
var model = new Book(instance);
// Fetch your model
model.fetch({
success: function(book) {
alert("BOOK : "+JSON.stringify(book));
model.set({reviews: book});
// Instansite your view, passing in your model
var view = new BookView({model: book, el: $('body')});
}
});