Introduction
Welcome to the "Demonstrate Backbone.js" article series. This article demonstrates how to create and use a Model in Backbone.js. This article starts with the concept of Backbone.js and various components of it. Our previous articles provided an introduction to Backbone.js. Part 1, Part 2 and Part 3 provided model implementation. You can read them from the following:
In this part we will see more about Model implementation in Backbone.js.
Here we will see how to bind a method with a property. We can fire any event or we can get notification if we bind a method with a Model property.
Notification about change in Model Property
In the following snippet we will bind a change method with the name property of a Product Model. Now the advantage is that when we change the name property, the bind trigger will be fired. Have a look at the following snippet.
<%@ 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>
Product = Backbone.Model.extend({
defaults: {
name: 'Xperia',
manufacturer: 'Sony'
},
initialize: function () {
this.bind("change:name", function (model) {
var name = model.get("name");
console.log("Changed Brand name to:- " + name);
});
}
});
var product = new Product({});
product.set({ name: 'Apple' });
</script>
</form>
</body>
</html>
Here we are binding the name property with a callback function within the initialize block and we are changing the name property outside of the mode.
Here is the sample output.
Notification about change in entire Model object
We can also bind the entire Model object to the callback function. In the following snippet we are binding the entire object to the callback function.
<%@ 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>



Join the conversation! Your thoughts help the community grow.