Open In App

Backbone.js urlRoot Model

The backbone.js urlRoot Model is used when we are using a Model outside the collection. The urlRoot will be used to make the url where the model reside on the server. We can use urlRoot as property and function in both ways. 

Syntax:



model.urlRoot
or 
model.urlRoot()

Properties: 

Example 1: In this example, we will illustrate the Backbone.js urlRoot model. Here we will use urlRoot as the address for the data and fetch the data for the model.






<!DOCTYPE html>
<html>
  
<head>
    <title>BackboneJS urlRoot Model</title>
    <script src=
    </script>
    <script src=
            type="text/javascript">
    </script>
    <script src=
            type="text/javascript">
    </script>
</head>
  
<body>
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
    
    <h3>BackboneJS urlRoot property of model Model</h3>
      
      <script type="text/javascript">
        var Person = Backbone.Model.extend({
            urlRoot:
                'https://jsonplaceholder.typicode.com/users'
        });
        
        // The instance with id attributes
        var person = new Person();
        person.fetch();
        console.log(person.attributes)
    </script>
</body>
  
</html>

Output: Following we can see the url of resource and the data we fetch form server:

Backbone.js urlRoot model

Example 2: In this example, we will use urlRoot as a function and append some attributes in url of the data.




<!DOCTYPE html>
<html>
  
<head>
    <title>BackboneJS urlRoot Model</title>
    <script src=
    </script>
    <script src=
            type="text/javascript">
    </script>
    <script src=
            type="text/javascript">
    </script>
</head>
  
<body>
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
    <h3>BackboneJS urlRoot of model as function</h3>
    <script type="text/javascript">
        var Person = Backbone.Model.extend({
            urlRoot: function () {
                return
                'https:.../posts' + '/' + 
                  this.get('postId')
                    + "/" + this.get('tag');
            },
        });
  
        // The instance with id attributes
        var person = new Person({ 
              postId: 1, 
              tag: 'comments' 
        });
        person.fetch();
        console.log("url is ", person.url());
        console.log(person.attributes);
    </script>
</body>
  
</html>

Output:

Backbone.js urlRoot model

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


Article Tags :