Introduction

This article explains how to add various items in a list in backbone.js. Here we have a TextBox in which we enter the desired items and click on the button then it wll add the item to the list.

backbone.js is a JavaScript library for client-side applications. It helps for managing the code for the developers that use this code to create a Single Page Application.

Now see the example:

  1. First create an application:

Create Web Application

  1. Now Add an HTML Page.

Add HTML Page

change Name

Add the following code:

<!DOCTYPE HTML>

<html>

<head>

<title>Backbone js example</title>

<script type="text/javascript"

src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>

<script type="text/javascript"

src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>

<script type="text/javascript"

src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>

<script type="text/javascript"

src="scripts/Hello.js"></script>

</head>

<body>

<input type="text" placeholder="Add new Item List" id="input" />

<button id="add-input">Add Item</button>

<ul id="item-list"></ul>

</body>

</html>

  1. Now add the Scripting file to the Project:

Add javascript file

Add the following code:

$(function () {

ItemList = Backbone.Collection.extend({

initialize: function () {

}

});

ItemView = Backbone.View.extend({

tagName: 'li',

events: {

'click #add-input': 'getItem'

},

initialize: function () {

var thisView = this;

this.itemlist = new ItemList;

_.bindAll(this, 'render');

this.itemlist.bind("add", function (model) {

thisView.render(model);

})

},

getItem: function () {

var item_Name = $('#input').val();

this.itemlist.add({ name: item_Name });

},

render: function (model) {

$("#item-list").append("<li>" +

model.get("name") + "</li>");

console.log('rendered')

}

});

var view = new ItemView({ el: 'body' });

});

In the code above we have created an "ItemList" for adding the items.

The "getItem" method takes the input and adds the items into the ItemLIst.

The initialize method is defined since the View model registered itself to the model collection event.

The render method is used for displaying the list.

  1. Now the HTML page is executed first by setting the property using "Start as startup project".

Set Html as start first

  1. Now execute the application:

Display Textbox

Enter the value in the text box and click on the button..

Add new items