What is Backbone.Model?
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.
- 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>
- Create a new backbone model.
var Chocolate = Backbone.Model.extend();
- Define an instance of our model.
var choc1 = new Chocolate();
- Use the
.setmethod to assign some values to variables. The variablenamerefers to the name of the chocolate, andPricerefers to the price of the chocolate.
// set the name and price of the chocolate
choc1.set({ name: "KitKat", Price: 20});
- Use the
.getmethod to get the values of variables.
// get the name and price of the choclate
var p = choc1.get("Price");
var n = choc1.get("name");
Free Resources