Wednesday, July 10, 2013

Backbone overview

Overview of Backbone:

Backbone.js is lightweight JS framework for developing web applications in a easier and structured way.

This article explains the steps involved in order to setup a project using backbone.js, underscore.js and require.js.

underscore.js is a templating based js framework similar to jquery templates. require.js is used to load the javascript modules dynamically.

In backbone, you represent your data as models, presentation related logic as views. If you are planning to create an Student creation page, then you will have StudentModel representing the employee data, employee.html which will contain the web page content, and StudentCreateView.js which will handle all the logic related to the web page such as Employee loading, saving validation, event handling etc.,

By following this approach, there is a clear role separation between the web page creator and the person who handles the presentation logic.

Example:

StudentModel.js
define([ 'jquery', 'underscore', 'backbone' ],
function($, _, Backbone) {
var Student = Backbone.Model.extend({
url:'student',
initialize : function() {
},
validate : function() {
}
});
return Student;
});
Require.js has a keyword called define to define a module, the array parameters are nothing but the framework or modules that this model depends on. In our case StudentModel depends on jquery, underscore and backbone. But this is not pointing to a js - as you can see, it is just a string. These string values can be mapped to the actual js using require.config

require.config({
paths : {
jquery : 'framework/lib/jquery/jquery-1.9.1.min',
underscore : 'framework/lib/underscore/underscore-min',
backbone : 'framework/lib/backbone/backbone-min',
text: 'framework/lib/require/text',
json : 'framework/lib/json/json2'
},
        ...
this way we dont need to mention the full path every time.

Backbone follows a REST based approach, hence the model has an attribute called url, which will be mapped to the controller. Backbone provides methods such as save, delete which will inturn invoke the url with the appropriate request headers.
in our case, when you say studentmodel.save, this will inturn invoke the url /student with post parameter.

Web page: StudentCreateTemplate.html
<div class="container scrollspy">
<form class="form-horizontal" id="frmStudentCreate">
<div class="row">
<div class="span6">
<div class="control-group">
<label class="control-label">Enrollment number * </label>
<div class="controls">
<input type="text" id="txtEnrollmentNumber" required="true">
</div>
</div>
</div>
</div>
<div class="row">
<div class="span6">
<div class="control-group">
<label class="control-label">First Name * </label>
<div class="controls">
<input type="text" id="txtStudentFirstName" required="true">
</div>
</div>
</div>
<div class="span6">
<div class="control-group">
<label class="control-label">Last Name * </label>
<div class="controls">
<input type="text" id="txtStudentLastName" required="true">
</div>
</div>
</div>
</div>
<div class="row">

<div class="span12">
<button class="btn btn-default btn-success" type="button"
id="btnSaveStudent">Save</button>
</div>
</div>
</form>
</div>

Screenshot:


As you can see in this file, there is no onclick, or validation or any javascript code, these will be handled in the view for better role separation:

Now, time to move on to the creation logic (View part):
StudentCreateView.js
define([ 'jquery', 'underscore', 'backbone',
'text!app/templates/StudentCreateTemplate.html',
'app/collections/StandardCollection', 'app/collections/SectionCollection', 'app/models/StudentModel' ],

function($, _, Backbone, StudentCreateTemplate, StandardCollection, SectionCollection, StudentModel) {
// Start your code here

var StudentCreateView = Backbone.View.extend({

initialize : function() {
this.model = new StudentModel();
this.model.url = "student"; // -- set the model url to student, this can be set during model creation time or usage time. 

},
el : $('#mainBody'),

render : function() {
$(this.el).html(StudentCreateTemplate);
},
events : {
'click #btnSaveStudent' : 'saveStudent',
'click #btnResetStudent' : 'resetStudent'
},
saveStudent : function() { // -- save click event is handled here..
this.setModelValues();
this.model.save(null, { // saving the model, this inturn calls the save method in the backbone, which inturn makes a call to the server with url "/student" and with POST attributes
success : function(student) { // callback method that will be called once the controller returns a success message.
alert('Student details saved' + student.get('id'));
}
});
},
setModelValues : function() { // mapping between the dom elements with the model. 
this.model.set({
rollNumber: $("#txtEnrollmentNumber").val(),
firstName: $("#txtStudentFirstName").val(),
lastName: $("#txtStudentLastName").val()
});
}
});
return StudentCreateView;
});

If you want to include the student creation page, then write the below code. 
var studentCreateViewObject = new StudentCreateView();
studentCreateViewObject.render();


This will render the page, Once the user enters the details and clicks on save, the data will be sent to the database.



No comments:

Post a Comment