Demonstrating Backbone.js: Implement View

Introduction

Welcome to the "Demonstrating Backbone.js" article series. This article demonstrates how to create and use a View in Backbone.js.

The objective of the article is to focus on view functionality and how to use views with a JavaScript templating library.

In order to implement Backbone.js we need to add jQuery because backbone needs jQuery or some other DOM library and of course we also need the backbone.js library.
To create a view and call the constructor method we have created a “View” that is extended from the View class of the Backbone.js library.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs" Inherits="JavaScript.JavaScript" %>

 

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

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

    <script src="backbone/underscore-min.js"></script>

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

</head>

<body>

    <form id="form1" runat="server">

    <script>

        model = new Backbone.Model({

            data: [

{ text: "Dotnetfunda", href: "http://dotnetfunda.com" },

{ text: "itfunda", href: "http://itfunda.com/" },

{ text: "kidsfunda", href: "http://kidsfunda.com" }

]

        });

        var View = Backbone.View.extend({

            initialize: function () {

                console.log('initializing');

            }

        });

        var view = new View();

    </script>

    </form>

</body>

</html>

Here is the output:

View class of Backbone
Passing Options

Here we have sent a blankoption which is directly accessible by this.options:
 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs" Inherits="JavaScript.JavaScript" %>

 

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

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

    <script src="backbone/underscore-min.js"></script>

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

</head>

<body>

    <form id="form1" runat="server">

    <script>

        model = new Backbone.Model({

            data: [

{ text: "CsharpCorner", href: "http://www.c-sharpcorner.com/" },

{ text: "asp.net", href: "http://www.asp.net/" },

{ text: "RamaSagar", href: "http://www.ramasagar.com/" }

]

        });

        var View = Backbone.View.extend({

            initialize: function () {

                console.log(this.options.blankoption);

            }

        });

        var view = new View({ blankoption: "empty string" });

    </script>

    </form>

</body>

</html>

 
Output

Passing Options

Summary

In this article, I explained how to create a view and call it using a constructor. In future articles we will understand more about Views with examples.

Next article: Demonstrating Backbone.js: Implement View Part 1

 

Up Next
    Ebook Download
    View all
    Learn
    View all