Backbone Model Methods — Advanced Data Operations
In this tutorial, you will learn about Backbone Model Methods. We cover key concepts, practical examples, and best practices to help you master this topic.
Backbone Models provide methods for the full data lifecycle: fetch retrieves data from the server, save persists changes, destroy removes records, and utility methods like toJSON, clone, has, and escape help manage attributes safely.
What You'll Learn
You'll learn every important Backbone Model method, including sync operations (fetch, save, destroy), attribute utilities (has, escape, omit, pick), and Serialization (toJSON, clone).
Why It Matters
Knowing the complete Model API means you can handle data confidently. You will know exactly which method to call for every operation — from loading data to cleaning up deleted records.
Real-World Use
A help desk ticketing system uses fetch to load ticket details, save to update status, and destroy to delete spam tickets. The escape method safely renders user-submitted content without XSS vulnerabilities.
flowchart LR
A[fetch] --> B[Server GET]
B --> C[Populate attributes]
C --> D[save]
D --> E[Server POST/PUT]
E --> F[Update attributes]
F --> G[destroy]
G --> H[Server DELETE]
H --> I[Remove from collection]
fetch — Loading Data from the Server
fetch() sends a GET request to the Model's URL and populates its attributes with the response. It returns a jQuery Deferred promise.
var User = Backbone.Model.extend({
urlRoot: '/api/users'
});
var user = new User({ id: 42 });
user.fetch({
success: function(model, response) {
console.log('User loaded:', model.get('name'));
console.log('Email:', model.get('email'));
},
error: function(model, response) {
console.error('Failed to load user:', response.statusText);
}
});
Expected output (assuming server returns {id:42, name:"Bob", email:"bob@example.com"}):
User loaded: Bob
Email: bob@example.com
save — Creating and Updating Records
save() determines whether to create or update based on the Model's id. If id exists, it sends PUT. If not, it sends POST.
var Task = Backbone.Model.extend({
urlRoot: '/api/tasks',
defaults: { title: '', completed: false }
});
// Creating a new task (POST /api/tasks)
var newTask = new Task({ title: 'Write documentation' });
newTask.save(null, {
success: function(model, response) {
console.log('Created with id:', model.id);
console.log('Title:', model.get('title'));
}
});
// Updating an existing task (PUT /api/tasks/1)
var existingTask = new Task({ id: 1, title: 'Updated title' });
existingTask.save(null, {
success: function(model) {
console.log('Updated:', model.get('title'));
}
});
Expected output:
Created with id: 101
Title: Write documentation
Updated: Updated title
save with Specific Attributes
Pass attribute overrides directly to save() to update only certain fields.
var Task = Backbone.Model.extend({
urlRoot: '/api/tasks'
});
var task = new Task({ id: 5, title: 'Review PR', completed: false });
// Only send the completed attribute
task.save({ completed: true }, {
patch: true,
success: function() {
console.log('Task completed:', task.get('completed'));
}
});
Expected output:
Task completed: true
destroy — Removing Records
destroy() sends a DELETE request and fires destroy and remove events. The Model is removed from any Collection it belongs to.
var Task = Backbone.Model.extend({
urlRoot: '/api/tasks'
});
var task = new Task({ id: 3 });
task.on('destroy', function() {
console.log('Task was destroyed');
});
task.destroy({
success: function(model, response) {
console.log('Server confirmed deletion');
console.log('Model isNew:', model.isNew());
}
});
Expected output:
Task was destroyed
Server confirmed deletion
Model isNew: true
toJSON — Serialization
toJSON() returns a shallow copy of the Model's attributes as a plain object. Use it for serialization, templating, or sending data to server.
var Task = Backbone.Model.extend({
defaults: {
title: '',
completed: false,
tags: []
}
});
var task = new Task({
title: 'Buy groceries',
completed: false,
tags: ['personal', 'urgent']
});
var data = task.toJSON();
console.log(data);
console.log(typeof data);
Expected output:
{ title: 'Buy groceries', completed: false, tags: ['personal', 'urgent'] }
object
Utility Methods
Backbone Models include several utility methods for safe attribute handling.
var User = Backbone.Model.extend({
defaults: {
name: '',
bio: '',
role: 'viewer'
}
});
var user = new User({
name: 'Alice',
bio: '<script>alert("xss")</script>'
});
// Check if attribute exists
console.log('Has name:', user.has('name'));
console.log('Has email:', user.has('email'));
// Safe HTML escaping
console.log('Escaped bio:', user.escape('bio'));
// Get changed attributes since last set
user.set('role', 'admin');
console.log('Changed:', user.changedAttributes());
// Clone entire model
var cloned = user.clone();
console.log('Clone name:', cloned.get('name'));
Expected output:
Has name: true
Has email: false
Escaped bio: <script>alert("xss")</script>
Changed: { role: 'admin' }
Clone name: Alice
isNew and previousAttributes
isNew() returns true if the Model has no id. previousAttributes() returns the state before the last change.
var Task = Backbone.Model.extend({
defaults: { title: '', status: 'pending' }
});
var task = new Task({ title: 'First task' });
console.log('Is new:', task.isNew());
task.set('title', 'Updated task');
console.log('Previous:', task.previous('title'));
console.log('Previous all:', task.previousAttributes());
Expected output:
Is new: true
Previous: First task
Previous all: { title: 'First task', status: 'pending' }
Common Mistakes
- Calling
save()without a URL or urlRoot. Backbone throws an error if it cannot determine where to send the request. Always defineurlRooton Models that use save. - Assuming
save()returns model directly.save()returns a jQuery promise, not the Model. Use the success callback or.then()to access the response. - Not handling save errors. Network failures and validation errors cause
save()to fail silently if no error callback is provided. Always handle both success and error. - Using
destroy()without waiting for server confirmation. The Model is not actually removed until the server responds. Wait for the success callback before updating the UI. - Mutating the result of
toJSON().toJSON()returns a reference to the attributes object. Mutating it mutates the Model. Call_.clone(model.toJSON())for a safe copy.
Practice Questions
- What HTTP method does
save()use when a Model has anid? - How do you prevent
save()from sending unchanged attributes? - What does
isNew()check? - Why should you use
escape()instead ofget()when rendering user content? - Challenge: Create a Model that fetches data from
/api/config, then saves a updated value back. Handle both success and error cases with console logs.
FAQ
Mini Project
Build a simple CRUD interface for a Product Model. Use fetch to load a product by ID, save to update price and quantity, and destroy to delete it. Log every operation result to the console.
What's Next
Learn about Backbone Model Validation to ensure data integrity. Then study Backbone Collections to manage groups of Models.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro