Backbone Models — Storing and Managing Data
In this tutorial, you will learn about Backbone Models. We cover key concepts, practical examples, and best practices to help you master this topic.
Backbone Models are the core data containers in a Backbone application. They store attributes, fire events when data changes, validate input, and sync with persistence layers. Every piece of application data should live inside a Model.
What You'll Learn
You'll learn how to define Backbone Models, set default attributes, use get and set methods, listen for changes, and understand the Model lifecycle.
Why It Matters
Models separate data from presentation. When data lives in a Model, every View that depends on it can react to changes automatically. This prevents the scattered, inconsistent state that plagues jQuery-heavy applications.
Real-World Use
In a network monitoring dashboard, each alert is a Model with attributes like severity, timestamp, hostname, and status. When a new alert arrives from the server, the Model updates and the alert View re-renders instantly.
flowchart LR
A[Define Model] --> B[Set Attributes]
B --> C[Validate]
C --> D{Valid?}
D -->|Yes| E[Fire change event]
D -->|No| F[Fire error event]
E --> G[Views update]
F --> H[Show validation error]
Defining a Model
Use Backbone.Model.extend() to create a Model class. Pass an object with properties like defaults, validate, and custom methods.
var Task = Backbone.Model.extend({
defaults: {
title: '',
completed: false,
priority: 'medium',
createdAt: null
}
});
var task = new Task();
console.log(task.toJSON());
Expected output:
{ title: '', completed: false, priority: 'medium', createdAt: null }
Working with Attributes
Use get() to read attributes and set() to update them. Never assign directly with model.attribute = value — that bypasses events.
var Task = Backbone.Model.extend({
defaults: {
title: '',
completed: false
}
});
var task = new Task({ title: 'Write documentation' });
console.log('Title:', task.get('title'));
console.log('Completed:', task.get('completed'));
task.set('completed', true);
console.log('After set:', task.get('completed'));
task.set({
title: 'Write API docs',
priority: 'high'
});
console.log('Bulk set:', task.get('title'), task.get('priority'));
Expected output:
Title: Write documentation
Completed: false
After set: true
Bulk set: Write API docs high
Listening to Model Changes
Models fire a change event when an attribute updates. You can listen for specific attributes or all changes.
var Task = Backbone.Model.extend({
defaults: { title: '', completed: false }
});
var task = new Task({ title: 'Learn Backbone' });
// Listen for any change
task.on('change', function() {
console.log('Something changed:', this.changedAttributes());
});
// Listen for a specific attribute
task.on('change:completed', function(model, value) {
console.log('Completed changed to:', value);
});
task.set('completed', true);
task.set('title', 'Master Backbone');
Expected output:
Completed changed to: true
Something changed: { completed: true }
Something changed: { title: 'Master Backbone' }
Initialization and Lifecycle
The initialize function runs when a new Model instance is created. Use it to set up default state, bind events, or fetch initial data.
var Alert = Backbone.Model.extend({
defaults: {
severity: 'info',
message: '',
timestamp: null
},
initialize: function() {
console.log('Alert created:', this.get('message'));
// Auto-set timestamp if not provided
if (!this.get('timestamp')) {
this.set('timestamp', new Date().toISOString());
}
this.on('change:severity', this.handleSeverityChange);
},
handleSeverityChange: function(model, value) {
console.log('Severity changed to:', value);
if (value === 'critical') {
console.log('CRITICAL ALERT — notify on-call engineer');
}
}
});
var alert = new Alert({ message: 'Disk usage at 95%' });
alert.set('severity', 'critical');
Expected output:
Alert created: Disk usage at 95%
Severity changed to: critical
CRITICAL ALERT — notify on-call engineer
Model IDs and URLs
Each Model has an id attribute that uniquely identifies it. The urlRoot property tells Backbone where to send REST requests for this model.
var User = Backbone.Model.extend({
urlRoot: '/api/users',
defaults: {
name: '',
email: ''
}
});
var user = new User({ id: 1, name: 'Alice', email: 'alice@example.com' });
console.log('Model URL:', user.url());
Expected output:
Model URL: /api/users/1
Common Mistakes
- Direct property assignment instead of
set(). Writingmodel.title = 'new'does not trigger events. Views never update. Always usemodel.set('title', 'new'). - Storing nested objects without change tracking. Backbone only fires change events for the top-level attribute. Changing a property inside a nested object does not trigger
change. Clone and replace the entire object. - Using
toJSON()for display.model.toJSON()returns a shallow copy of attributes. It is safe for Serialization but usemodel.get()for individual attribute access in Views. - Overwriting the entire Model reference. Doing
model = new Model()breaks all existing event bindings. Update the existing model instance instead of replacing it. - Forgetting to call the parent initialize. If you override
initialize, callBackbone.Model.Prototype.initialize.apply(this, arguments)to preserve parent behavior.
Practice Questions
- What happens when you assign a value directly with
model.attribute = value? - How do you listen for changes to a specific attribute?
- What is the purpose of the
defaultsproperty? - How does the
url()method determine the REST endpoint for a Model? - Challenge: Create a
WeatherReadingModel with attributes for temperature, humidity, and timestamp. Add a custom methodisHot()that returns true when temperature exceeds 30. Create an instance and call the method.
FAQ
Mini Project
Create a Config Model that stores application settings (theme, language, notifications). Add methods to toggle each setting. Listen for changes and log them. Initialize it with values from localStorage if they exist.
What's Next
Now that you understand Models, learn about Backbone Model Methods for advanced data operations. Then explore Backbone Model Validation to ensure data integrity.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro