Open In App

Backbone.js isNew Model

Last Updated : 13 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn about the Backbone.js isNew model. The isNew model is used to represent a new state, which is when the details are not yet saved to the server. It will return a Boolean value. If it is true, it will return true, otherwise false.

Syntax:

Backbone.Model.isNew()

Parameters: It method does not accept any parameters.

Example 1: In this example, we will check if the book attribute is new using isNew.

HTML
<!DOCTYPE html>
<html>

<head>
    <script type="text/javascript" src=
"https://code.jquery.com/jquery-2.1.3.min.js">
    </script>
    <script type="text/javascript" src=
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js">
    </script>
    <script type="text/javascript" src=
"https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js">
    </script>
</head>

<body>
    <script type="text/javascript">
        var Books = Backbone.Model.extend();
        var book = new Books(
          { book_name: "css", price: 900, type: "web" }
        );

        document.write(book.isNew());
    </script>
</body>

</html>

Output:

true

Example 2: In this example, we will check if the book attribute is new using isNew. It will return false as the ID has been set after it had been saved.

HTML
<!DOCTYPE html>
<html>

<head>
    <script type="text/javascript" src=
"https://code.jquery.com/jquery-2.1.3.min.js">
    </script>
    <script type="text/javascript" src=
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js">
    </script>
    <script type="text/javascript" src=
"https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js">
    </script>
</head>

<body>
    <script type="text/javascript">
        var Books = Backbone.Model.extend();
        var book = new Books();

          // Logic for saving to the server
        Backbone.sync = function (method, model) {
            model.set('id', 100);
        };
        book.save();
      
        // Will return false as the ID has
        // been set after it had been saved
        document.write(book.isNew())
    </script>
</body>

</html>

Output:

false

Reference: https://backbonejs.org/#Model-isNew


Next Article

Similar Reads