backbone.jsHow do I create a model in Backbone.js?
Backbone.js provides an MVC framework for creating models. To create a model, you first need to define a model class using the Backbone.Model.extend
method. This method takes an object as an argument, which defines the model's attributes and methods.
For example:
var Person = Backbone.Model.extend({
defaults: {
name: 'John Doe',
age: 30
}
});
This defines a Person
model class with two attributes: name
and age
.
You can then instantiate a model object from this class like so:
var person = new Person();
console.log(person.get('name')); // Outputs 'John Doe'
The person
object now has the attributes name
and age
set to the default values defined in the Person
model class.
You can also set and get the model's attributes using the set
and get
methods:
person.set('name', 'Jane Doe');
console.log(person.get('name')); // Outputs 'Jane Doe'
You can also define custom methods on the model class which can be used to manipulate the model's attributes:
var Person = Backbone.Model.extend({
defaults: {
name: 'John Doe',
age: 30
},
increaseAge: function(){
this.set('age', this.get('age') + 1);
}
});
var person = new Person();
person.increaseAge();
console.log(person.get('age')); // Outputs 31
For more information on creating models in Backbone.js, see the Backbone.js documentation.
More of Backbone.js
- How do I use a template engine with Backbone.js?
- How do I use W3Schools to learn Backbone.js?
- How do I create tabs using Backbone.js?
- How do I create a sample application using Backbone.js?
- How do I use Backbone.js to create a YouTube video player?
- How do I use Backbone.js to create a wiki?
- How do Backbone.js and Express differ in their usage for software development?
- How can I migrate from Backbone.js to React?
- How can I use a template in Backbone.js?
- How can I use Backbone.js to render a view?
See more codes...