Home Manual Reference Source Repository
import ParseModel from 'backbone/src/ParseModel.js'
public class | source

ParseModel

You can directly use instance of this class. parseModel

Extends:

EventsModel → ParseModel

Direct Subclass:

AppState, Item

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

This implementation of Backbone.Model is backed by a ParseObject. If a ParseObject is not provided in options then a className for the associated table must be defined as options.className or a getter method such as get className() { return '<CLASSNAME>'; }. All methods that trigger synchronization return an ES6 Promise or a ParsePromise. This includes the following methods: destroy, fetch, save. Rather than passing in a error or success callback one can use promises to post a follow up chain of actions to complete.

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-Parse-ES6 supports the older "extend" functionality of the Parse SDK. 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. Refer to modelExtend which provides the "extend" functionality for ParseModel. It differs from the standard Backbone extend functionality such that the first parameter requires a class name string for the associated table.

It is recommended though to use ES6 syntax for working with Backbone-Parse-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.

Please see the Model documentation for relevant information about the parent class / implementation.

Example:

import Backbone from 'backbone';

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

older extend example:
export default Backbone.Model.extend('<CLASSNAME>',
{
   initialize: { alert('initialized!); }
});
The following methods return a promise - destroy, fetch, save. An example on using promises for save:

model.save().then(() =>
{
   // success
},
(error) =>
{
   // error
});

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

Parse class name

public

A potentially associated collection.

public

id: *

Update the id.

public

Parse proxy ParseObject

public

Object hash of name / class to register as sub classes.

public

The value returned during the last failed validation.

Method Summary

Public Methods
public

clone(): *

Returns a new instance of the model with identical attributes.

public

destroy(options: object): Promise | ParsePromise

Destroys the model on the server by delegating delete request to Backbone.sync and the associated ParseObject.

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

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. This implementation requires a ParseObject and the attributes are directly taken from the attributes of the ParseObject. To keep parity with the Parse SDK the ID of the ParseObject is set as this.id.

public

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

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 and potentially on the associated ParseObject.

public

Return a copy of the model's attributes object.

public

url()

This is an unsupported operation for backbone-parse-es6.

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.

From class Model
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.

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

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

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

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:

Model#constructor

Params:

NameTypeAttributeDescription
attributes object

Optional attribute hash of original values to set.

options object

Optional parameters

Public Members

public attributes: object source

The hash of attributes for this model.

Override:

Model#attributes

public changed: object source

A hash of attributes whose current and previous value differ.

Override:

Model#changed

public cid: number source

Client side ID

Override:

Model#cid

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.

Override:

Model#cidPrefix

public className: string source

Parse class name

public collection: Collection source

A potentially associated collection.

Override:

Model#collection

public id: * source

Update the id.

Override:

Model#id

public parseObject: BackboneParseObject source

Parse proxy ParseObject

public subClasses: object source

Object hash of name / class to register as sub classes.

public validationError: * source

The value returned during the last failed validation.

Override:

Model#validationError

Public Methods

public clone(): * source

Returns a new instance of the model with identical attributes.

Override:

Model#clone

Return:

*

See:

public destroy(options: object): Promise | ParsePromise source

Destroys the model on the server by delegating delete request to Backbone.sync and the associated ParseObject. Returns ParsePromise or ES6 Promise 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, 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.

Override:

Model#destroy

Params:

NameTypeAttributeDescription
options object

Provides optional properties used in destroying a model.

Return:

Promise | ParsePromise

Example:

book.destroy().then(() => {
   // do something
};

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.

Override:

Model#isNew

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. This implementation requires a ParseObject and the attributes are directly taken from the attributes of the ParseObject. To keep parity with the Parse SDK the ID of the ParseObject is set as this.id.

Override:

Model#parse

Params:

NameTypeAttributeDescription
resp object

ParseObject

options object

May include options.parseObject.

Return:

object

Attributes from the ParseObject.

See:

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

Save a model to your database (or alternative persistence layer), by delegating to Backbone.sync. Returns a Promise. 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 particular this method is overridden to be able to support resolving Parse.Pointer deserializing which requires the deserialized data to be parsed by the associated models.

Override:

Model#save

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:

Promise

Example:

const book = new Backbone.Model({
   title: 'The Rough Riders',
   author: 'Theodore Roosevelt'
   className: 'Book'
});

book.save();

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

or use full ES6 syntax:

class Book extends Backbone.Model
{
   get className() { return 'Book'; }
   get subClass() { return Book; }     // If subClass is set this class will be registered with Parse.
}                                      // Object.registerSubclass()

const book = new Book({
   title: 'The Rough Riders',
   author: 'Theodore Roosevelt'
});

See:

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

Set a hash of attributes (one or many) on the model and potentially on the associated ParseObject. 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. In addition option.updateParseObject may contain a boolean to indicate whether the associated ParseObject should be updated.

Override:

Model#set

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 toJSON(): object source

Return a copy of the model's attributes object.

Override:

Model#toJSON

Return:

object

JSON representation of this model.

public url() source

This is an unsupported operation for backbone-parse-es6.

Override:

Model#url