Home Manual ReferenceGraphs Source Repository
import Model from 'backbone-es6/src/Model.js'
public class | source

Model

Extends:

Events → Model

Direct Subclass:

ParseModel, ParseModel

Backbone.Model - Models are the heart of any JavaScript application. (http://backbonejs.org/#Model)

Models are the heart of any JavaScript application, containing the interactive data as well as a large part of the logic surrounding it: conversions, validations, computed properties, and access control.

Backbone-ES6 supports the older "extend" functionality of Backbone. You can still use "extend" to extend Backbone.Model with your domain-specific methods, and Model provides a basic set of functionality for managing changes.

It is recommended though to use ES6 syntax for working with Backbone-ES6 foregoing the older "extend" mechanism.

Create a new model with the specified attributes. A client id (cid) is automatically generated & assigned for you.

If you pass a {collection: ...} as the options, the model gains a collection property that will be used to indicate which collection the model belongs to, and is used to help compute the model's url. The model.collection property is normally created automatically when you first add a model to a collection. Note that the reverse is not true, as passing this option to the constructor will not automatically add the model to the collection. Useful, sometimes.

If {parse: true} is passed as an option, the attributes will first be converted by parse before being set on the model.

Underscore methods available to Model:

See:

Example:

import Backbone from 'backbone';

export default class MyModel extends Backbone.Model
{
   initialize() { alert('initialized!); }
}

older extend example:
export default Backbone.Model.extend(
{
   initialize: { alert('initialized!); }
});
Another older extend example... The following is a contrived example, but it demonstrates defining a model with a
custom method, setting an attribute, and firing an event keyed to changes in that specific attribute. After running
this code once, sidebar will be available in your browser's console, so you can play around with it.

var Sidebar = Backbone.Model.extend({
   promptColor: function() {
      var cssColor = prompt("Please enter a CSS color:");
      this.set({color: cssColor});
   }
});

window.sidebar = new Sidebar;

sidebar.on('change:color', function(model, color) {
   $('#sidebar').css({ background: color });
});

sidebar.set({color: 'white'});

sidebar.promptColor();
The above extend example converted to ES6:

class Sidebar extends Backbone.Model {
   promptColor() {
      const cssColor = prompt("Please enter a CSS color:");
      this.set({ color: cssColor });
   }
}

window.sidebar = new Sidebar();

sidebar.on('change:color', (model, color) => {
   $('#sidebar').css({ background: color });
});

sidebar.set({ color: 'white' });

sidebar.promptColor();
Another older extend example:
extend correctly sets up the prototype chain, so subclasses created with extend can be further extended and
sub-classed as far as you like.

var Note = Backbone.Model.extend({
   initialize: function() { ... },

   author: function() { ... },

   coordinates: function() { ... },

   allowedToEdit: function(account) {
      return true;
   }
});

var PrivateNote = Note.extend({
   allowedToEdit: function(account) {
      return account.owns(this);
   }
});
Converting the above example to ES6:

class Note extends Backbone.Model {
   initialize() { ... }

   author() { ... }

   coordinates() { ... }

   allowedToEdit(account) {
      return true;
   }
}

class PrivateNote extends Note {
   allowedToEdit(account) {
      return account.owns(this);
   }
});

let privateNote = new PrivateNote();
A huge benefit of using ES6 syntax is that one has access to 'super'

class Note extends Backbone.Model {
   set(attributes, options) {
      super.set(attributes, options);
      ...
   }
});

Constructor Summary

Public Constructor
public

constructor(attributes: object, options: object)

When creating an instance of a model, you can pass in the initial values of the attributes, which will be set on the model.

Member Summary

Public Members
public

The hash of attributes for this model.

public

A hash of attributes whose current and previous value differ.

public

Client side ID

public

The prefix is used to create the client id which is used to identify models locally.

public

A potentially associated collection.

public

id: *

Update the id.

public

The value returned during the last failed validation.

Method Summary

Public Methods
public

Retrieve a hash of only the model's attributes that have changed since the last set, or false if there are none. Optionally, an external attributes hash can be passed in, returning the attributes in that hash which differ from the model. This can be used to figure out which portions of a view should be updated, or what calls need to be made to sync the changes to the server.

public

clear(options: object): *

Removes all attributes from the model, including the id attribute.

public

clone(): *

Returns a new instance of the model with identical attributes.

public

Destroys the model on the server by delegating an HTTP DELETE request to Backbone.sync.

public

escape(attr: *): string

Similar to get, but returns the HTML-escaped version of a model's attribute. If you're interpolating data from the model into HTML, using escape to retrieve attributes will prevent XSS attacks.

public

fetch(options: object): *

Merges the model's state with attributes fetched from the server by delegating to Backbone.sync. Returns a jqXHR. Useful if the model has never been populated with data, or if you'd like to ensure that you have the latest server state.

public

get(attr: *): *

Get the current value of an attribute from the model.

public

has(attr: string): boolean

Returns true if the attribute is set to a non-null or non-undefined value.

public

hasChanged(attr: string): *

Has the model changed since its last set? If an attribute is passed, returns true if that specific attribute has changed.

public abstract

Initialize is an empty function by default.

public

Has this model been saved to the server yet? If the model does not yet have an id, it is considered to be new.

public

isValid(options: object): boolean

Run validate to check the model state.

public

Special-cased proxy to the _.matches function from Underscore.

public

parse(resp: object, options: object): object

parse is called whenever a model's data is returned by the server, in fetch, and save. The function is passed the raw response object, and should return the attributes hash to be set on the model. The default implementation is a no-op, simply passing through the JSON response. Override this if you need to work with a preexisting API, or better namespace your responses.

public

previous(attr: string): *

During a "change" event, this method can be used to get the previous value of a changed attribute.

public

Return a copy of the model's previous attributes. Useful for getting a diff between versions of a model, or getting back to a valid state after an error occurs.

public

save(key: key | object, val: *, options: object): *

Save a model to your database (or alternative persistence layer), by delegating to Backbone.sync.

public

set(key: object | string, val: * | object, options: object): *

Set a hash of attributes (one or many) on the model.

public

sync(): *

Uses Backbone.sync to persist the state of a model to the server.

public

Return a shallow copy of the model's attributes for JSON stringification. This can be used for persistence, serialization, or for augmentation before being sent to the server. The name of this method is a bit confusing, as it doesn't actually return a JSON string — but I'm afraid that it's the way that the JavaScript API for JSON.stringify works.

public

unset(attr: object | string, options: object): *

Remove an attribute by deleting it from the internal attributes hash.

public

url(): string

Returns the relative URL where the model's resource would be located on the server. If your models are located somewhere else, override this method with the correct logic. Generates URLs of the form: "[collection.url]/[id]" by default, but you may override by specifying an explicit urlRoot if the model's collection shouldn't be taken into account.

Delegates to Collection#url to generate the URL, so make sure that you have it defined, or a urlRoot property, if all models of this class share a common root URL. A model with an id of 101, stored in a Backbone.Collection with a url of "/documents/7/notes", would have this URL: "/documents/7/notes/101"

Protected Methods
protected

_validate(attrs: object, options: object): boolean

Run validation against the next complete set of model attributes, returning true if all is well.

Inherited Summary

From class Events
public

bind(): *

Delegates to on.

public

listenTo(obj: object, name: string, callback: function): Events

Tell an object to listen to a particular event on an other object.

public

listenToOnce(obj: object, name: string, callback: function): Events

Just like listenTo, but causes the bound callback to fire only once before being removed.

public

off(name: string, callback: function, context: object): Events

Remove a previously-bound callback function from an object.

public

on(name: string, callback: function, context: object): *

Bind a callback function to an object.

public

once(name: string, callback: function, context: object): *

Just like on, but causes the bound callback to fire only once before being removed.

public

stopListening(obj: object, name: string, callback: function): Events

Tell an object to stop listening to events.

public

Trigger callbacks for the given event, or space-delimited list of events.

public

unbind(): *

Delegates to off.

Public Constructors

public constructor(attributes: object, options: object) source

When creating an instance of a model, you can pass in the initial values of the attributes, which will be set on the model. If you define an initialize function, it will be invoked when the model is created.

Override:

Events#constructor

Params:

NameTypeAttributeDescription
attributes object

Optional attribute hash of original keys / values to set.

options object

Optional parameters

Example:

new Book({
   title: "One Thousand and One Nights",
   author: "Scheherazade"
});
ES6 example: If you're looking to get fancy, you may want to override constructor, which allows you to replace
the actual constructor function for your model.

class Library extends Backbone.Model {
   constructor() {
      super(...arguments);
      this.books = new Books();
   }

   parse(data, options) {
      this.books.reset(data.books);
      return data.library;
   }
}

See:

Public Members

public attributes: object source

The hash of attributes for this model.

public changed: object source

A hash of attributes whose current and previous value differ.

public cid: number source

Client side ID

public cidPrefix: string source

The prefix is used to create the client id which is used to identify models locally. You may want to override this if you're experiencing name clashes with model ids.

public collection: Collection source

A potentially associated collection.

public id: * source

Update the id.

public validationError: * source

The value returned during the last failed validation.

Public Methods

public changedAttributes(diff: object): object | boolean source

Retrieve a hash of only the model's attributes that have changed since the last set, or false if there are none. Optionally, an external attributes hash can be passed in, returning the attributes in that hash which differ from the model. This can be used to figure out which portions of a view should be updated, or what calls need to be made to sync the changes to the server.

Params:

NameTypeAttributeDescription
diff object

A hash of key / values to diff against this models attributes.

Return:

object | boolean

See:

public clear(options: object): * source

Removes all attributes from the model, including the id attribute. Fires a "change" event unless silent is passed as an option.

Params:

NameTypeAttributeDescription
options object

Optional parameters.

Return:

*

See:

public clone(): * source

Returns a new instance of the model with identical attributes.

Return:

*

See:

public destroy(options: object): boolean | XMLHttpRequest source

Destroys the model on the server by delegating an HTTP DELETE request to Backbone.sync. Returns a jqXHR object, or false if the model isNew. Accepts success and error callbacks in the options hash, which will be passed (model, response, options). Triggers a "destroy" event on the model, which will bubble up through any collections that contain it, a "request" event as it begins the Ajax request to the server, and a "sync" event, after the server has successfully acknowledged the model's deletion. Pass {wait: true} if you'd like to wait for the server to respond before removing the model from the collection.

Params:

NameTypeAttributeDescription
options object

Provides optional properties used in destroying a model.

Example:

book.destroy({success: function(model, response) {
   ...
}});

See:

public escape(attr: *): string source

Similar to get, but returns the HTML-escaped version of a model's attribute. If you're interpolating data from the model into HTML, using escape to retrieve attributes will prevent XSS attacks.

Params:

NameTypeAttributeDescription
attr *

Defines a single attribute key to get and escape via Underscore.

Return:

string

Example:

let hacker = new Backbone.Model({
   name: "<script>alert('xss')</script>"
});

alert(hacker.escape('name'));

See:

public fetch(options: object): * source

Merges the model's state with attributes fetched from the server by delegating to Backbone.sync. Returns a jqXHR. Useful if the model has never been populated with data, or if you'd like to ensure that you have the latest server state. Triggers a "change" event if the server's state differs from the current attributes. fetch accepts success and error callbacks in the options hash, which are both passed (model, response, options) as arguments.

Params:

NameTypeAttributeDescription
options object

Optional parameters.

Return:

*

Example:

// Poll every 10 seconds to keep the channel model up-to-date.
setInterval(function() {
   channel.fetch();
}, 10000);

See:

public get(attr: *): * source

Get the current value of an attribute from the model.

Params:

NameTypeAttributeDescription
attr *

Defines a single attribute key to get a value from the model attributes.

Return:

*

Example:

For example:
note.get("title")

See:

public has(attr: string): boolean source

Returns true if the attribute is set to a non-null or non-undefined value.

Params:

NameTypeAttributeDescription
attr string

Attribute key.

Return:

boolean

Example:

if (note.has("title")) {
   ...
}

See:

public hasChanged(attr: string): * source

Has the model changed since its last set? If an attribute is passed, returns true if that specific attribute has changed.

Note that this method, and the following change-related ones, are only useful during the course of a "change" event.

Params:

NameTypeAttributeDescription
attr string

Optional attribute key.

Return:

*

Example:

book.on("change", function() {
   if (book.hasChanged("title")) {
      ...
   }
});

See:

public abstract initialize() source

Initialize is an empty function by default. Override it with your own initialization logic.

See:

public isNew(): boolean source

Has this model been saved to the server yet? If the model does not yet have an id, it is considered to be new.

Return:

boolean

See:

public isValid(options: object): boolean source

Run validate to check the model state.

Params:

NameTypeAttributeDescription
options object

Optional hash that may provide a validationError field to pass to invalid event.

Return:

boolean

Example:

class Chapter extends Backbone.Model {
   validate(attrs, options) {
      if (attrs.end < attrs.start) {
      return "can't end before it starts";
   }
}

let one = new Chapter({
   title : "Chapter One: The Beginning"
});

one.set({
   start: 15,
   end:   10
});

if (!one.isValid()) {
   alert(one.get("title") + " " + one.validationError);
}

See:

public matches(attrs: object | string): boolean source

Special-cased proxy to the _.matches function from Underscore.

Params:

NameTypeAttributeDescription
attrs object | string

Predicates to match

Return:

boolean

See:

public parse(resp: object, options: object): object source

parse is called whenever a model's data is returned by the server, in fetch, and save. The function is passed the raw response object, and should return the attributes hash to be set on the model. The default implementation is a no-op, simply passing through the JSON response. Override this if you need to work with a preexisting API, or better namespace your responses.

Params:

NameTypeAttributeDescription
resp object

Usually a JSON object.

options object

Unused

Return:

object

Pass through to set the attributes hash on the model.

See:

public previous(attr: string): * source

During a "change" event, this method can be used to get the previous value of a changed attribute.

Params:

NameTypeAttributeDescription
attr string

Attribute key used for lookup.

Return:

*

Example:

let bill = new Backbone.Model({
   name: "Bill Smith"
});

bill.on("change:name", function(model, name) {
   alert("Changed name from " + bill.previous("name") + " to " + name);
});

bill.set({name : "Bill Jones"});

See:

public previousAttributes(): * source

Return a copy of the model's previous attributes. Useful for getting a diff between versions of a model, or getting back to a valid state after an error occurs.

Return:

*

See:

public save(key: key | object, val: *, options: object): * source

Save a model to your database (or alternative persistence layer), by delegating to Backbone.sync. Returns a jqXHR if validation is successful and false otherwise. The attributes hash (as in set) should contain the attributes you'd like to change — keys that aren't mentioned won't be altered — but, a complete representation of the resource will be sent to the server. As with set, you may pass individual keys and values instead of a hash. If the model has a validate method, and validation fails, the model will not be saved. If the model isNew, the save will be a "create" (HTTP POST), if the model already exists on the server, the save will be an "update" (HTTP PUT).

If instead, you'd only like the changed attributes to be sent to the server, call model.save(attrs, {patch: true}). You'll get an HTTP PATCH request to the server with just the passed-in attributes.

Calling save with new attributes will cause a "change" event immediately, a "request" event as the Ajax request begins to go to the server, and a "sync" event after the server has acknowledged the successful change. Pass {wait: true} if you'd like to wait for the server before setting the new attributes on the model.

In the following example, notice how our overridden version of Backbone.sync receives a "create" request the first time the model is saved and an "update" request the second time.

Params:

NameTypeAttributeDescription
key key | object

Either a key defining the attribute to store or a hash of keys / values to store.

val *

Any type to store in model.

options object

Optional parameters.

Return:

*

Example:

Backbone.sync = (method, model) => {
   alert(method + ": " + JSON.stringify(model));
   model.set('id', 1);
};

let book = new Backbone.Model({
   title: "The Rough Riders",
   author: "Theodore Roosevelt"
});

book.save();

book.save({author: "Teddy"});

See:

public set(key: object | string, val: * | object, options: object): * source

Set a hash of attributes (one or many) on the model. If any of the attributes change the model's state, a "change" event will be triggered on the model. Change events for specific attributes are also triggered, and you can bind to those as well, for example: change:title, and change:content. You may also pass individual keys and values.

Params:

NameTypeAttributeDescription
key object | string

Either a string defining a key or a key / value hash.

val * | object

Either any type to store or the shifted options hash.

options object

Optional parameters.

Return:

*

Example:

note.set({ title: "March 20", content: "In his eyes she eclipses..." });

book.set("title", "A Scandal in Bohemia");

See:

public sync(): * source

Uses Backbone.sync to persist the state of a model to the server. Can be overridden for custom behavior.

Return:

*

See:

public toJSON(): object source

Return a shallow copy of the model's attributes for JSON stringification. This can be used for persistence, serialization, or for augmentation before being sent to the server. The name of this method is a bit confusing, as it doesn't actually return a JSON string — but I'm afraid that it's the way that the JavaScript API for JSON.stringify works.

Return:

object

JSON representation of this model.

Example:

let artist = new Backbone.Model({
   firstName: "Wassily",
   lastName: "Kandinsky"
});

artist.set({ birthday: "December 16, 1866" });

alert(JSON.stringify(artist));

See:

public unset(attr: object | string, options: object): * source

Remove an attribute by deleting it from the internal attributes hash. Fires a "change" event unless silent is passed as an option.

Params:

NameTypeAttributeDescription
attr object | string

Either a key defining the attribute or a hash of keys / values to unset.

options object

Optional parameters.

Return:

*

See:

public url(): string source

Returns the relative URL where the model's resource would be located on the server. If your models are located somewhere else, override this method with the correct logic. Generates URLs of the form: "[collection.url]/[id]" by default, but you may override by specifying an explicit urlRoot if the model's collection shouldn't be taken into account.

Delegates to Collection#url to generate the URL, so make sure that you have it defined, or a urlRoot property, if all models of this class share a common root URL. A model with an id of 101, stored in a Backbone.Collection with a url of "/documents/7/notes", would have this URL: "/documents/7/notes/101"

Return:

string

See:

Protected Methods

protected _validate(attrs: object, options: object): boolean source

Run validation against the next complete set of model attributes, returning true if all is well. Otherwise, fire an "invalid" event.

Params:

NameTypeAttributeDescription
attrs object

attribute hash

options object

Optional parameters

Return:

boolean