Demonstrating Backbone.js: Implement Model Part 4

Introduction

Welcome to the "Demonstrating Backbone.js" article series. This article series starts with the concept of Backbone.js and various components of it. The previous articles were an introduction to Backbone.js and Part 1, Part 2 and Part 3 were model implementations that you can get it from here:

  1. Introduction of Backbone.js
  2. Demonstrating Backbone.js: Implement Model
  3. Demonstrating Backbone.js: Implement Model Part-2
  4. Demonstrating Backbone.js: Implement Model Part-3

In this article we will see more about Model implementations in Backbone.js.

Clear Method of Model object

We can use the clear() method of the Model class to clear the model properties. It will clear all the defined properties of the Backbone Model.

<%@ 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: 'Macbook',
            manufacturer: 'Apple'
        }
    });
    var product = new Product({});
    console.log('Name is :- ' + product.get('name'));
    product.clear();
    console.log('After using clear() method:- ' + product.get('name'));

</
script>
</
form>
</
body>
</
html>

The following is the sample output.

gyu
Clone model object using Clone() function

Here we used the clone() method to copy one Model object to another object. In the following snippet we are using the clone() method to copy a property of the “product” object into “productp1”.

<%@ 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({
    });

    var product = new Product({ name: 'Iphone', manufacturer: 'Apple' });

    var productp1 = product.clone();

    console.log('Name is :- ' + productp1.get('name'));

    console.log('Manufacturer :- ' + productp1.get('manufacturer'));

</
script>
</
form>
</
body>
</
html>

Here is the sample output.

clone
Summary


In this article, I explained how to implement a Model in Backbone.js. We also saw how to clear a model's object data .Then, we saw how to clone the model object using the clone() function.
In future articles we will understand more about Models with examples. I hope you have liked it. Happy coding.


Similar Articles