Overview of Basic Backbone.js Concepts
Backbone.js provides structure to web applications in 4 ways...
// Model
var Employee = Backbone.Model.extend({
urlRoot: '/employee/'
});
var employee = new Employee();
// Collection
var Employees = Backbone.Collection.extend({
url: '/employee',
model: Employee
});
var employees = new Employees();
// create an instance of the employee model
var newHire = new Employee();
// create a generic JavaScript object and add a function to it
var im_listening = {};
im_listening.processData = function() {
alert('The new employee's name is: ' + newHire.get('FirstName') + newHire.get('LastName'))
};
// extend the generic JavaScript object with Backbone.js's event object
_.extend(im_listening, Backbone.Events);
// tell our object to listen to the model's sync event
im_listening.listenTo(newHire, 'sync', im_listening.processData);
// fetch data for that model from API, will trigger the "sync" event
newHire.set('id',136);
newHire.fetch();
// View - Detail
var EmployeeDetailView = Backbone.View.extend({
events: {
'click #btnLoad': 'loadEmployee'
},
el: '#employeeViewContainer',
initialize: function() {
this.model = new Employee();
this.listenTo(this.model, 'sync', this.render);
},
loadEmployee: function() {
var id = this.$('#employeeID').val();
this.model.set('id', id);
this.model.fetch();
},
render: function () {
var name = this.model.get('FirstName') + ' '
+ this.model.get('LastName');
this.$('#employeeName').html(name);
}
});
var employeeDetailView = new EmployeeDetailView();
// Application Router
var Router = Backbone.Router.extend({
routes: {
// 'URN in address bar' : 'function on this object to call when URL matches'
'': "index", // http://application.com/
'employee/:id': 'employee' // http://application.com/employee/6
},
index: function() {
var employeeListView = new EmployeeListView();
},
employee: function(id) {
var employeeDetailView = new EmployeeDetailView({'id':id});
}
});