Backbone.js fetch Model

In this article, we will see Backbone.js fetch() model. The Backbone.js fetch() model is used to merge the state of the model with fetched attributes by accepting the model data from the server by delegating the sync() method in the given model.

Syntax:

Backbone.Model.fetch(options);

Parameters: It accepts single parameter value:

  • options: It specifies parameters such as id, name etc. that are used in a model.

Example 1: This example shows the fetch() model for the “book” model data.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script src=
"https://code.jquery.com/jquery-2.1.3.min.js"
            type="text/javascript">
    </script>
    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js"
            type="text/javascript">
    </script>
    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"
            type="text/javascript">
    </script>    
</head>
  
<body>
    <script type="text/javascript"
      
        Backbone.sync = function(method1, mymodel) {  
            document.write(JSON.stringify(mymodel));  
        }; 
        var Books = Backbone.Model.extend();  
        var book = new Books({bookid:23}); 
             
        book.fetch();   
    </script
</body>
</html>


Output:

{"bookid":23}

Example 2: This example shows the fetch() model for the “book” model attributes.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script src=
"https://code.jquery.com/jquery-2.1.3.min.js"
            type="text/javascript">
    </script>
    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js"
            type="text/javascript">
    </script>
    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"
            type="text/javascript">
    </script>    
</head>
  
<body>
    <script type="text/javascript"
      
        Backbone.sync = function(method1, mymodel) {  
            document.write(JSON.stringify(mymodel));  
        }; 
        var Books = Backbone.Model.extend();  
        var book = new Books({bookid:23,price:678,book_name:'php'}); 
             
        book.fetch();   
    </script
</body>
</html>


Output:

{"bookid":23,"price":678,"book_name":"php"}

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



Contact Us