$(function () {
// Create a model for the courses
var Course = Backbone.Model.extend({
// These contain three attributes.
// Here their default values
defaults: {
title: 'My Courses',
price: 100,
checked: false
},
toggle: function () {
this.set('checked', !this.get('checked'));
}
});
// Collection of Courses
var CourseList = Backbone.Collection.extend({
// Will hold objects of the Course model
model:Course,
getChecked: function () {
return this.where({ checked: true });
}
});
var courses = new CourseList([
new Course({ title: '.NET Developer', price: 200 }),
new Course({ title: 'web designing', price: 250 }),
new Course({ title: 'Software Testing', price: 100 }),
new Course({ title: 'Java developer', price: 10 })
]);
var CourseView = Backbone.View.extend({
tagName: 'li',
events: {
'click': 'toggleCourse'
},
initialize: function () {
this.listenTo(this.model, 'change', this.render);
},
render: function () {
this.$el.html('<input type="checkbox" value="1" name="' + this.model.get('title') + '" /> ' + this.model.get('title') + '<span>$' + this.model.get('price') + '</span>');
this.$('input').prop('checked', this.model.get('checked'));
return this;
},
toggleCourse: function () {
this.model.toggle();
}
});
var App = Backbone.View.extend({
el: $('#main'),
initialize: function () {
this.total = $('#total span');
this.list = $('#courses');
this.listenTo(courses, 'change', this.render);
courses.each(function (course) {
var view = new CourseView({ model: course });
this.list.append(view.render().el);
}, this);
},
render: function () {
var total = 0;
_.each(courses.getChecked(), function (elem) {
total += elem.get('price');
});
this.total.text('$' + total);
return this;
}
});
new App();
});