Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

backbone js
backbone model

What is Backbone.Model?

Educative Answers Team

Models are the heart of any JavaScript application. They contain the interactive data as well as a large part of the logic surrounding it: conversions, validations, computed properties, and access control. A user can extend Backbone.Model by using various domain-specific methods. The role of the Model is to provide a basic set of functionality for managing changes in our Backbone.Model.

How to use it

We use the syntax Backbone.Model.extend to create a new model class. .extend provides Backbone.Model with relevant properties of instances and class properties such as the use of constructor, etc. Moreover, .extend sets up a prototype chain and can create an inheritance model. It’s functionality is similar to classes.

Code

Let’s look at the example for defining chocolates in a candy shop.

  1. Declare the following sources and links to allow any user to use backbone methods and resources.
<script src= 
"https://code.jquery.com/jquery-3.1.0.min.js"></script> 

script src= 
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script> 
  
<script src= 
"https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>

  1. Create a new backbone model.
var Chocolate = Backbone.Model.extend();
  1. Define an instance of our model.
var choc1 = new Chocolate();
  1. Use the .set method to assign some values to variables. The variable name refers to the name of the chocolate, and Price refers to the price of the chocolate.
// set the name and price of the chocolate
choc1.set({ name: "KitKat", Price: 20});
  1. Use the .get method to get the values of variables.
// get the name and price of the choclate
var p = choc1.get("Price"); 
var n = choc1.get("name");

RELATED TAGS

backbone js
backbone model
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring