This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Understanding collections in Backbone.js</title> | |
</head> | |
<body> | |
<div id="container"></div> | |
<script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script> | |
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js" type="text/javascript"></script> | |
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js" type="text/javascript"></script> | |
<script type="text/javascript"> | |
var Student = Backbone.Model.extend({}); | |
var StudentView = Backbone.View.extend({ | |
tagName: 'div', | |
studentTemplate: _.template( "<label> Name : </label><label><%= name %></label></b></b><label> Age : </label><label><%= age %></label>" ), | |
render: function(){ | |
this.$el.html( this.studentTemplate(this.model.toJSON())); | |
return this; | |
} | |
}); | |
var StudentsCollection = Backbone.Collection.extend({model: Student}); | |
var StudentsView = Backbone.View.extend({ | |
el: '#container', | |
render: function(){ | |
var self = this; | |
this.collection.each(function(student){ | |
var studentView = new StudentView({ model: student }); | |
self.$el.append(studentView.render().el); | |
}); | |
return this; | |
} | |
}); | |
var sharuk = new Student({name: 'Sharuk khan', age: 26 }); | |
var sanjay = new Student({name: 'Sanjay kumar', age: 27 }); | |
var students = new StudentsCollection(); | |
students.add(sharuk); | |
students.add(sanjay); | |
var studentsView = new StudentsView({ collection: students }); | |
studentsView.render(); | |
</script> | |
</body> | |
</html> |