Introduction
Welcome to the "Demonstrating Backbone.js" article series. This article demonstrates how to create and use collections in Backbone.js. This article starts with the concept of Backbone.js and various components of it. Previous articles have provided an introduction to views and the implementation of routers and collections. You can get them from the following:
In this article we will see a few more concepts of collections in Backbone.js.
Binding and unbinding in collections
Here we have bound the “add” method to the “Product” collection.
<%@ 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 type="text/javascript" src="backbone/Jquery.js"></script>
<script type="text/javascript" src="backbone/underscore-min.js"></script>
<script type="text/javascript" src="backbone/backbone-min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<script>
var Product = new Backbone.Collection;
Product.bind("add", function (Product) {
console.log("Name Added:-" + Product.get("name"));
});
Product.add([
{ name: "Iphone" },
{ name: "Xperia" }
]);
</script>
</form>
</body>
</html>
Output
Unbinding
We can unbind any specific method from a Collection. The unbind() function takes an event name as a parameter as shown below.
<script>
var Product = new Backbone.Collection;
Product.bind("add", function (Product) {
console.log("Name Added:-" + Product.get("name"));
});
Product.bind('remove', function (Product) {
console.log("Name " + Product.get('name') + ' Deleted from collection');
});
Product.add([
{ name: "Iphone" },
{ name: "Xperia" }
]);
Product.remove(Product.at(0).cid);
</script>
Output
Summary
In this article, I explained how to use collections in Backbone.js. In future articles we will understand more about Collections with examples.
Previous article: Demonstrating Backbone.js :Implement Collections Part 4