Listening To DOM Events in Backbone.js

Introduction

This article explains DOM events in backbone.js. How they work in Backbone and how to create an application that listens for DOM events in backbone.js. In this tutorial we can do the following:

  • We can see the list of users.
  • We can edit the user name.
  • We can add the new user name.
  • We can delete the existing user.

Now create the DOM event using an application:

  1. Create a web application as in the following:
  • Start Visual Studio 2013, from the Start window select "New Project".
  • Select "Installed" -> "Template" -> "Visual C#" -> "Web" -> "Visual Studio 2012" and select "Empty Web Application".

Create Web Application

  • Click on the "OK" button.
  1. Now add the HTML page.
  • In the Solution Explorer.
  • Right-click on the project then select "Add" -> "HTML page".

Add HTML Page

  • Change the name of the page.

Change Name

  • Click on the "Add" button.

Add the following code:

<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8">

    <title></title>

</head>

<body>

    <form id="addUser" action="">

        <input type="text" placeholder="Name of the user">

        <input type="submit" value="Add User">

    </form>

    <script id="userTemplate" type="text/template">

        <span><strong><%= name %></strong> (<%= age %>) - <%= occupation %></span>

        <button class="edit">Edit</button>

        <button class="delete">Delete</button>

    </script>

    <script src="js/underscore.js"></script>

    <script src="js/jquery.js"></script>

    <script src="js/backbone.js"></script>

    <script src="js/app.js"></script>

</body>

</html>

  1. Now add a folder in the project with the name "js" and add the following script file in this folder.
  • In the Solution Explorer right-click on the js folder.
  • Select "Add" -> "New Item".
  • Now select "JavaScript".

Add JavaScript file

  •  Click on the "Ok" button.

Add the following code:

(function () {

    window.App = {

        Models: {},

        Collections: {},

        Views: {}

    };

    window.template = function (id) {

        return _.template($('#' + id).html());

    };

    // User Model

    App.Models.User = Backbone.Model.extend({

        defaults: {

            name: 'New Client',

            age: 28,

            occupation: 'Employee'

        }

    });

    // A List of Employee

    App.Collections.Employee= Backbone.Collection.extend({

        model: App.Models.User

    });

    // View for all employee

    App.Views.Employee = Backbone.View.extend({

        tagName: 'ul',

        initialize: function () {

            this.collection.on('add'this.addOne, this);

        },

        render: function () {

            this.collection.each(this.addOne, this);

            return this;

        },

        addOne: function (user) {

            var userView = new App.Views.User({ model: user});

            this.$el.append(userView.render().el);

        }

    });

    // The View for a User

    App.Views.User = Backbone.View.extend({

        tagName: 'li',

        template: template('userTemplate'),

        initialize: function () {

            this.model.on('change'this.render, this);

            this.model.on('destroy'this.remove, this);

        },

        events: {

            'click .edit''editUser',

            'click .delete''DestroyUser'

        },

        editUser: function () {

            var newName = prompt("Enter the new name of client"this.model.get('name'));

            if (!newName) return;

            this.model.set('name', newName);

        },

        DestroyUser: function () {

            this.model.destroy();

        },

        remove: function () {

            this.$el.remove();

        },

        render: function () {

            this.$el.html(this.template(this.model.toJSON()));

            return this;

        }

    });

    App.Views.AddUser = Backbone.View.extend({

        el: '#addUser',

        events: {

            'submit''submit'

        },

        submit: function (e) {

            e.preventDefault();

            var newUserName = $(e.currentTarget).find('input[type=text]').val();

            var user = new App.Models.User({ name: newUserName });

            this.collection.add(user);

        }

    });

    var employeeCollection = new App.Collections.Employee([

        {

            name: 'Smith Patel',

            age: 25

        },

        {

            name: 'Jhon farnandis',

            age: 24,

            occupation: '.NET Developer'

        },

        {

            name: 'Mahak Ahuja',

            age: 26,

            occupation: 'Web Designer'

        }

    ]);

    var addUserView = new App.Views.AddUser({ collection: employeeCollection });

    employeeView = new App.Views.Employee({ collection: employeeCollection });

    $(document.body).append(employeeView.render().el);

})();

 

  1. Now execute the application. In this application we can add a new user, edit an existing user and delete an existing user.

Display list of user

Add new user

Edit Existing User

Delete existing User

 

Up Next
    Ebook Download
    View all
    Learn
    View all