Handling DOM events in Backbone.js and working with Collections

Posted by: Mahesh Sabnis , on 3/24/2014, in Category Backbone.js
Views: 34236
Abstract: The Backbone.js library allows you to develop responsive web applications with clear separation of Model and View. DOM Events associated with Collection helps to notify the UI elements about Updates and accordingly to display refreshed data

Backbone.js is a lightweight JavaScript library loosely based on the Model-View-Controller (MVC) pattern (it’s not an MVC framework) and it allows developers to create single-page web applications. We covered some basics of Backbone in a previous article Getting Started with Backbone.js and Rendering a Collection using View

To manage data of web applications, Backbone provides a Model creation strategy. The model allows us to define properties to contain data and business logic. The Collection declaration allows to store collection of the data, which is later used by the View.

 

In Backbone, the View (UI) is generally rendered using HTML Templates, and elements declared in this Template are accessible to View, but it might be possible that the HTML page (or MVC view or .aspx) already contains HTML elements and you need to handle the DOM events for these elements. The question then is how to handle them? In the following implementation, we will see that the ‘click’ event for the html button element is handled inside the View object. The method which gets executed for the click event is used to add the model object into the collection and then the collection is rendered using HTML Table.

Step 1: Open Visual Studio 2012/2013 or any Editor of your choice and create a new web application (an empty ASP.NET app if you are using Visual Studio). In this project, add Backbone and jQuery libraries using the NuGet Package.

Step 2: Add a new folder and name it as ‘Backbone_Custom_Scripts’. In this folder, add a new JavaScript file and name it as Model.js. Define the following Model and Collection objects in Model.js

var Employee = Backbone.Model.extend({
    defaults: {
        EmpNo: 0,
        EmpName: "",
        DeptName: "",
        Designation:"",
        Salary:0.0
    }
});

//Declaring Employee Collection
var EmployeesCollection = Backbone.Collection.extend({
  model: Employee
});

Step 3: Add a new HTML page in the project and name it as ‘H4_Adding_Data_To_Collection_DOM_Events.html’ or anything simpler. Add the following script reference in it:

<script src="Scripts/jquery-2.0.3.min.js"></script>
< script src="Scripts/underscore.min.js"></script>
< script src="Scripts/backbone.min.js"></script>
< script src="Backcone_Custom_Scripts/Models.js"></script>

Step 4: In the <body> tag of the page, add a <table> and in the table add Textboxes and Buttons. Add a <div> tag below the table to render collection:

<table style="width:100%;" id="tblinput">
< tr>
    <td>EmpNo:</td>
    <td>
        <input type="text" id="txteno" placeholder="EmpNo is Numeric" />
    </td>
< /tr>
< tr>
    <td>EmpName:</td>
    <td>
        <input type="text" id="txtename" placeholder="EmpName is Text" />
    </td>
< /tr>
< tr>
    <td>DeptName:</td>
    <td>
        <input type="text" id="txtdname" placeholder="DeptName is Text" />
    </td>
< /tr>
< tr>
    <td>Designation:</td>
    <td>
        <input type="text" id="txtdesig" placeholder="Designation is Text" />
    </td>
< /tr>
< tr>
    <td>Salary:</td>
    <td>
        <input type="text" id="txtsal" placeholder="Salary is Numeric" />
    </td>
< /tr>
< tr>
    <td>
        <button id="btnadd">Add</button>
    </td>
    <td>
        <button id="btnclear">Clear</button>
    </td>
    <td>
        <input type="checkbox" id="ckbksort" value="Sory by Name" />
    </td>
< /tr>
< /table>
< div id="dvcontainer"></div>

Step 5: Add the script in the <body> tag below the <div> with id ‘dvcontainer’,  This will define the View object as shown here:

var EmployeeRecordsView = Backbone.View.extend({
//The body element in which all elements are displayed
el: 'body',
//Events for the elements on the page.
events:{
    'click button#btnadd': 'addData',
    'click button#btnclear': 'clearInput'
},

//Render function to display collection collection in the Table
render: function () {
    var dvcontainer = $(this.el).find('#dvcontainer');
        var viewHtml = '<table border="1">';
        viewHtml += "<tr><td>EmpNo</td><td>EmpName</td><td>DeptName</td><td>Designation</td> <td>Salary</td></tr>";
        //Iterate through the collection
        _.each(this.collection.models, function (m, i, l) {
            var empRecHtml = '<tr><td>' + m.get('EmpNo') + '</td><td>' + m.get('EmpName') + '</td><td>' + m.get('DeptName') + '</td><td>' + m.get('Designation') + '</td><td>' + m.get('Salary') + '</td></tr>';
            viewHtml += empRecHtml;
        });
        viewHtml += '</table>';
    dvcontainer.html(viewHtml);
},

//Function executed on the button clieck
addData: function () {
    var newEmp = new Employee();
    newEmp.set('EmpNo', $("#txteno").val());
    newEmp.set('EmpName', $("#txtename").val());
    newEmp.set('DeptName', $("#txtdname").val());
    newEmp.set('Designation', $("#txtdesig").val());
    newEmp.set('Salary', $("#txtsal").val());
    EmpCollection.add(newEmp);
},

//Function to clear all textboxes.
clearInput: function () {
    //Clear all Textboxes
    $("#tblinput input").val('');
}
});

The above code has some important features:

  • The ‘el’ element is defined as ‘body’ to display all elements in it.
  • ‘events’ defines ‘click’ event for the button on the Page. These buttons are found using jQuery selector using #‘. Method is assigned to each event i.e. addData and clearInput.
  • The ‘render’ function defines the logic for finding the <div> having id as ‘dvContainer’. Once it is found, then the HTML table is generated by iterating through the collection passed to the view. (The code is provided in future steps).
  • The ‘addData’ method reads values entered in the Textboxes and using the ‘set’ method of the Backbone model, the value entered in the Textbox is passed to an individual property of the Employee Model object. The model is then added into the EmployeeCollection using ’add()’ method of the Backbone collection.
  • The ‘clearInput’ method clears all Textboxes.

Step 6: In the <script>, define the collection object and pass the collection to the View object as shown below:

//The Collection Object
var EmpCollection = new EmployeesCollection();
//The View Object and Pass Collection to it
var EmpsView = new EmployeeRecordsView({
    collection:EmpCollection
});

Step 7: Since we need to add data entered in Textboxes to the collection and render the data from collection in a Table, subscribe to the ‘add’ event of the collection and call ‘render’ method of the View in it. So when the collection is changed, a new row will be added in the table.

//Subscribe to the 'add' event of the collection
//When Collection changed
//Render the Updated Table View
EmpCollection.on('add', function () {
    EmpsView.render();
});

Step 8: View the page in browser

backbone-collection

Enter some data in each Textbox and click on ‘Add’. The data will get added in the Table as shown below:

backbone-add-collection

Click on the ‘Clear’ button to clear all Textboxes. Enter new record values in Textboxes and click on Add button and a new row will be added in the table:

add-new-row

Conclusion: The Backbone library allows you to develop responsive web applications with a clear separation of Model and View. Events associated with Collection helps to notify the UI elements about Updates and accordingly display refreshed data.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions), and Front-end technologies like Angular and React. Follow him on twitter @maheshdotnet or connect with him on LinkedIn


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by JJ on Monday, March 24, 2014 11:06 PM
I love the new backbone series
Comment posted by Federico Kereki on Sunday, August 10, 2014 10:48 AM
Good example, but a couple of points:

* the code, as is, won't run because of a typo:  "EmpsVeiw.render();" instead of "EmpsView.render();"

* why is there the (unused) "sort by name" checkbox?

* the opening tags shouldn't have a space, as in "< tr"

But the example is good, and helps understand Backbone!

Thanks, and best regards
Comment posted by Suprotim Agarwal on Thursday, August 14, 2014 12:04 AM
@Federico: Fixed Point 1. For point 3, our previous code editor did not escape table tags, so any code containing table html would get rendered as a table. We have upgraded and are updating all articles. So this will get fixed soon.
Comment posted by chayan on Tuesday, August 19, 2014 7:26 AM
It is working perfectly for me.This is a great example with proper explanation.I would like to thank you coz it will be great help for the beginners.
Comment posted by arun on Friday, April 24, 2015 7:44 AM
asasasas