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 can I use Backbone.js with React to build a web application?
- How can I use Backbone.js to solve a specific problem?
- ¿Cuáles son las ventajas y desventajas de usar Backbone.js para el desarrollo de software?
- How do I sort a collection in Backbone.js?
- How can I use Backbone.js to render a view?
- How can I use Backbone.js to customize a WordPress website?
- How do Backbone.js and Angular differ in terms of usage and features?
- How do I update a model in Backbone.js?
- How do I use a template engine with Backbone.js?
- How do I create a view in Backbone.js?
See more codes...