How to Create a Model in Backbone.js?


Backbone.js is a popular JavaScript framework that allows developers to create dynamic and interactive web applications Backbone.js's ability to build models that can be used to store and modify data is one of its primary strengths. In this article, we'll look at how to build a model in Backbone.js and how to apply it to a web application.

Creating a Model

Using the Backbone.Model class, you must first specify a new model before you can build one in Backbone.js. Here is an example of how to make a straightforward model called "Person" −

var Student = Backbone.Model.extend({
   defaults: {
      name: '',
      weight: 0
   }
});

In this instance, we're building a brand-new model called "Person" that contains the two predefined parameters "name" and "age." If one of these conditions is true, then the corresponding values for these attributes will be set to an empty string and 0.

Initializing a Model

Once your model has been defined, you can make new instances of it by calling the "new" keyword and the model's name. For example −

var john = new Student();

By doing this, a fresh instance of the "Person" model will be created with the parameters "name" and "age" set to their default values.

A model's function Object() { [native code] } can also be used to initialise a model with certain values by receiving an object holding those values as an argument. For instance −

var jane = new Student({name: 'Jane', weight: 25});

By doing this, a fresh instance of the "Student" model will be created with "name" set to "Jane" and "weight" set to 25.

Accessing Model Properties

Once you have created an instance of your model, you can access its properties using the "get" method. For example −

console.log(john.get('name'));
console.log(jane.get('name'));

Example

Below is complete implementation −

<html>
<head>
   <title>Example of Backbone.js</title>
   <script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.6/underscore-min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.4.1/backbonemin.js"></script>
</head>
<body>
   <div id= "name1"></div>
   <div id= "name2"></div>
   <script>
      var Student = Backbone.Model.extend({
         defaults: {
            name: '',
            weight: 0
         }
      });
      var john = new Student({name: 'john'});
      var jane = new Student({name: 'Jane', weight: 25});
      document.getElementById("name1").innerHTML = "First Person name is: " + john.get('name');
      document.getElementById("name2").innerHTML = "Second Person name is: " + jane.get('name');
   </script>
</body>
</html>

Output

First Person name is: john
Second Person name is: Jane

You can also set the value of a property using the "set" method. For example −

john.set('name', 'John');
console.log(john.get('name')); 

Example

<html>
<head>
   <title>Example of Backbone.js</title>
   <script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.6/underscore-min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.4.1/backbonemin.js"></script>
</head>
<body>
   <div id= "name"></div>
   <script>
      var Student = Backbone.Model.extend({
         defaults: {
            name: '',
            weight: 0
         }
      });
      var john = new Student();
      john.set('name', 'John');
      document.getElementById("name").innerHTML = "Student name is: " + john.get('name');
   </script>
</body>
</html>

Output

Student name is: John

Adding Validation to a Model

You may apply validation to your models with Backbone.js to make sure the data they contain is in the right format. You can do this by defining a "validate" method on your model. For example −

var Student = Backbone.Model.extend({
   defaults: {
      name: '',
      weight: 0
   },
   validate: function(attributes) {
      if (!attributes.name) {
         return 'Name is required';
      }
      if (attributes.weight < 0 || attributes.weight > 120) {
         return 'Weight must be between 0 and 120';
      }
   }
});

The "validate" method in this example verifies that the "name" property is not empty and that the "age" property is between 0 and 120. The "validate" method will produce an error message if one or both of these requirements are unsatisfied.

The model's properties can then be set using the "set" method, and you can check to see if the validation was successful or not. For example −

var john = new Student();
john.set({name: 'John', weight: 25}, {validate: true});
console.log(john.validationError); 

When we set the properties of John with valid properties, validation is passed, and no error is thrown.

var john = new Student();
jane.set({name: 'John', weight: 205}, {validate: true});
console.log(jane.validationError); 

When we set properties of John with some invalid property (here, weight is greater than 120), validation fails, and the error message is displayed.

Example

<html>
<head>
   <title>Example of Backbone.js</title>
   <script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.6/underscore-min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.4.1/backbonemin.js"></script>
</head>
<body>
   <script>
      var Student = Backbone.Model.extend({
         defaults: {name: '', weight: 0},
         validate: function(attributes) {
            if (!attributes.name) {
               return 'Name is required';
            }
            if (attributes.weight < 0 || attributes.weight > 120) {
               return 'Weight must be between 0 and 120';
            }
         }
      });
      var john = new Student();
      john.set({name: 'John', weight: 205}, {validate: true});
      document.write(john.validationError);
   </script>
</body>
</html>

Output

Weight must be between 0 and 120

Adding Custom Methods to a Model

You can also add custom methods to your models to perform specific tasks. For example −

greet: function() {
   console.log('Hello, my name is ' + this.get('name'));
   }
});

Example

<html>
<head>
   <title>Example of Backbone.js</title>
   <script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.6/underscore-min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.4.1/backbonemin.js"></script>
</head>
<body>
   <script>
      var Student = Backbone.Model.extend({
         defaults: {name: '', weight: 0},
         greet: function() {
            document.write('Hello, my name is ' + this.get('name'));
         }
      });
      var john = new Student({name: 'John'});
      john.greet();
   </script>
</body>
</html>

Output

Hello, my name is John

In this example, we are adding a "greet" method to the "Person" model that logs a message to the console.

Conclusion

A Backbone.js model is a powerful resource for manipulating and storing data in your online application. Setting default settings, validating data, and adding unique methods to carry out particular tasks are all possible by establishing a model. You may now use Backbone.js to build more intricate and dynamic applications after learning to design models.

Updated on: 06-Mar-2023

183 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements