Backbone.js: Events Cheat Sheet

onobject.on(event, callback, [context])Bind a callback function to an object. The callback will be invoked whenever the event is fired.[event], [callback], [context])Remove a previously-bound callback function from an object. 
triggerobject.trigger(event, [*args])Trigger callbacks for the given event, or space-delimited list of events.
onceobject.once(event, callback, [context])It extends the backbone.Model class while creating your own backbone Model.
listenToobject.listenTo(other, event, callback)Tell an object to listen to a particular event on an other object. 
stopListeningobject.stopListening([other], [event], [callback])Tell an object to stop listening to events.
listenToOnceobject.listenToOnce(other, event, callback)It causes the listenTo occur only once before the callback function is being removed.

Catalog of Events

  • “add” (model, collection, options) — when a model is added to a collection.
  • “remove” (model, collection, options) — when a model is removed from a collection.
  • “update” (collection, options) — single event triggered after any number of models have been added, removed or changed in a collection.
  • “reset” (collection, options) — when the collection’s entire contents have been reset.
  • “sort” (collection, options) — when the collection has been re-sorted.
  • “change” (model, options) — when a model’s attributes have changed.
  • “change:[attribute]” (model, value, options) — when a specific attribute has been updated.
  • “destroy” (model, collection, options) — when a model is destroyed.
  • “request” (model_or_collection, xhr, options) — when a model or collection has started a request to the server.
  • “sync” (model_or_collection, response, options) — when a model or collection has been successfully synced with the server.
  • “error” (model_or_collection, xhr, options) — when a model’s or collection’s request to the server has failed.
  • “invalid” (model, error, options) — when a model’s validation fails on the client.
  • “route:[name]” (params) — Fired by the router when a specific route is matched.
  • “route” (route, params) — Fired by the router when any route has been matched.
  • “route” (router, route, params) — Fired by history when any route has been matched.
  • “all” — this special event fires for any triggered event, passing the event name as the first argument followed by all trigger arguments.

Backbone.js: Model Cheat Sheet

MethodsSyntax & Description
extendBackbone.Model.extend(properties, [classProperties])To create a Model class of your own, you extend Backbone.Model and provide instance properties, as well as optional classProperties to be attached directly to the constructor function.
preinitializenew Model([attributes], [options])For use with models as ES classes. If you define a preinitialize method, it will be invoked when the Model is first created, before any instantiation logic is run for the Model.
constructor / initializenew Model([attributes], [options])When a model instance is created, the class’s constructor gets called and it is invoked by defining the initialize function when the model is created.
getmodel.get(attribute)Get the current value of an attribute from the model. 
setmodel.set(attributes, [options])Set a hash of attributes (one or many) on the model. 
escapemodel.escape(attribute)It is like the get function, but returns the HTML-escaped version of a model’s attribute.
hasmodel.has(attribute)Returns true
 if the attribute is set to a non-null or non-undefined value.
unsetmodel.unset(attribute, [options])Remove an attribute by deleting it from the internal attributes hash. Fires a “change”
 event unless silent
 is passed as an option.
clearmodel.clear([options])Removes all attributes from the model, including the id
 attribute. Fires a “change”
 event unless silent
 is passed as an option.
idmodel.idA special property of models, the id is an arbitrary string (integer id or UUID). If you set the id in the attributes hash, it will be copied onto the model as a direct property.
idAttributemodel.idAttributeDefines a model’s unique identifier which contains the name of the member of the class which will be used as id.
cidmodel.cidA special property of models, the cid or client id is a unique identifier automatically assigned to all models when they’re first created.
attributesmodel.attributesAttributes defines property of a model.
changedmodel.changedChanges all the attributes that have changed after setting the attributes using the set() method.
defaultsmodel.defaults or model.defaults()The defaults hash (or function) can be used to specify the default attributes for your model.
toJSONmodel.toJSON([options])Returns a copy of the attributes as an object for JSON stringification.
syncmodel.sync(method, model, [options])Uses Backbone.sync to persist the state of a model to the server. Can be overridden for custom behavior.
fetchmodel.fetch([options])Merges the model’s state with attributes fetched from the server by delegating to Backbone.sync[attributes], [options])Saves the data of the model by delegating to sync() method which reads and saves the model every time when a Backbone calls it.
destroymodel.destroy([options])Destroys or removes the model from the server by using the Backbone.sync method which delegates the HTTP “delete” request.
validatemodel.validate(attributes, options)If the input is invalid, it returns a specified error message or if the input is valid, it doesn’t specify anything and simply displays the result.
validationErrormodel.validationErrorThe value returned by validate during the last failed validation.
isValidmodel.isValid(options)Run validate to check the model state.
urlmodel.url()Returns the relative URL where the model’s resource would be located on the server.
urlRootmodel.urlRoot or model.urlRoot()Enables the url function by using the model id to generate the URL.
parsemodel.parse(response, options)Returns the model’s data by passing through the response object and represents the data in the JSON format.
clonemodel.clone()Returns a new instance of the model with identical attributes.
isNewmodel.isNew()Has this model been saved to the server yet? If the model does not yet have an id, it is considered to be new.
hasChangedmodel.hasChanged([attribute])Has the model changed since its last set? If an attribute is passed, returns true
 if that specific attribute has changed.
changedAttributesmodel.changedAttributes([attributes])It returns the model’s attributes that have changed since the last set or else becomes false, if there are no attributes.
previousmodel.previous(attribute)During a “change”
 event, this method can be used to get the previous value of a changed attribute.
previousAttributesmodel.previousAttributes()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.

Backbone.js: Collection Cheat Sheet

extendBackbone.Collection.extend(properties, [classProperties])Extends the backbone’s collection class to create a collection.
modelcollection.model([attrs], [options])To specify the model class, we need to override the model property of the collection class.
modelIdcollection.modelId(attrs)Override this method to return the value the collection will use to identify a model given its attributes.
preinitializenew Backbone.Collection([models], [options])For use with collections as ES classes. If you define a preinitialize method, it will be invoked when the Collection is first created and before any instantiation logic is run for the Collection.
constructor / initializenew Backbone.Collection([models], [options])When a model instance is created, it is invoked by defining the initialize function when the collection is created.
modelscollection.modelsRaw access to the JavaScript array of models inside of the collection.
toJSONcollection.toJSON([options])Return an array containing the attributes hash of each model in the collection.
synccollection.sync(method, collection, [options])It represents the state of the model and uses the Backbone.sync to display the state of the collection.
addcollection.add(models, [options])Add a model (or an array of models) to the collection, firing an “add”
 event for each model, and an “update”
 event afterwards.
removecollection.remove(models, [options])Remove a model (or an array of models) from the collection, and return them.
resetcollection.reset([models], [options])Adding and removing models one at a time is all well and good, but sometimes you have so many models to change that you’d rather just update the collection in bulk.
setollection.set(models, [options])The set method performs a “smart” update of the collection with the passed list of models. 
getcollection.get(id)It is used to retrieve the model from a collection by using the idor cid. the model from a collection by using specified index.
pushcollection.push(model, [options])Add a model at the end of a collection. Takes the same options as add.
popcollection.pop([options])Remove and return the last model from a collection. Takes the same options as remove.
unshiftcollection.unshift(model, [options])Add a model at the beginning of a collection. Takes the same options as add.
shiftcollection.shift([options])Remove and return the first model from a collection. Takes the same options as remove.
slicecollection.slice(begin, end)Return a shallow copy of this collection’s models, using the same options as native Array#slice.
lengthcollection.lengthLike an array, a Collection maintains a length
 property, counting the number of models it contains.
comparatorcollection.comparatorIt is used to sort the items in the collection.
sortcollection.sort([options])Sorts the items in the collection and uses comparator property in order to sort the items.
pluckcollection.pluck(attribute)Pluck an attribute from each model in the collection. Equivalent to calling map
 and returning a single attribute from the iterator.
wherecollection.where(attributes)Return an array of all the models in a collection that match the passed attributes. Useful for simple cases of filter
findWherecollection.findWhere(attributes)It returns the model, that matches the specified attribute in the collection.
urlcollection.url or collection.url()Set the url property (or function) on a collection to reference its location on the server.
parsecollection.parse(response, options)Returns the collection’s data by passing through the response object and represents the data in JSON format.
clonecollection.clone()Returns a new instance of the collection with an identical list of models.
fetchcollection.fetch([options])Fetch the default set of models for this collection from the server, setting them on the collection when they arrive. 
createcollection.create(attributes, [options])Convenience to create a new instance of a model within a collection. 
mixinBackbone.Collection.mixin(properties)mixin provides a way to enhance the base Backbone.Collection and any collections which extend it. 

Backbone.js: Router Cheat Sheet

extendBackbone.Router.extend(properties, [classProperties])It extends the backbone’s router class.
routesrouter.routesIt defines the URL representation of applications objects.
preinitializenew Backbone.Router([options])For use with routers as ES classes.
constructor / initializenew Router([options])It creates a new constructor for the router instantiation.
routerouter.route(route, name, [callback])It creates a route for the router.
navigaterouter.navigate(fragment, [options])It is used to update the URL in the applications.
executerouter.execute(callback, args, name)It is used when a route matches its corresponding callback.

Backbone.js: History Cheat Sheet


This is the only method which can be used to manipulate the BackboneJS-History. It starts listening to routes and manages the history for bookmarkable URL’s.



options: The options include the parameters such as pushState and hashChange used with history.

Backbone.js: Sync Cheat Sheet

Backbone.syncsync.(method, model, options)
It persists the state of the model to the server. Parameters:
method −  the CRUD method ("create""read""update", or "delete" )
model − the model to be saved (or collection to be read)
options − success and error callbacks, and all other jQuery request options
ajaxBackbone.ajax = function(request) { ... };It defines the custom ajax function.
emulateHTTPBackbone.emulateHTTP = trueIf your web server does not support REST or HTTP approach, then turn on the Backbone.emulateHTTP.
emulateJSONBackbone.emulateJSON = trueIt is used to handle the requests encoded with application/json by setting the method to true.

Backbone.js: Utility Cheat Sheet

Backbone.noConflictvar backbone = Backbone.noConflict();Returns the Backbone
 object back to its original value.
Backbone.$Backbone.$ = $;It allows Backbone to use particular object as DOM library.

Backbone.js: View Cheat Sheet

extendBackbone.View.extend(properties, [classProperties])properties − It provides instance properties for the view class.
classProperties − The classProperties attached to the view’s constructor function.
elview.elIt defines which element to be used as the view reference.
$elview.$elIt represents the jQuery object for the view’s element.
setElementview.setElement(element)It specifies existing DOM element to a different DOM element.
attributesview.attributesThey can be used as DOM element attributes on the view class.
$ (jQuery)view.$(selector)It is used as selector that contains $ function and runs queries within the view’s element.
templateview.template([data])While rendering the view, template creates reusable copies of markup and provides access to instance data.
renderview.render()It contains the logic for rendering a template.
removeview.remove()It is used to remove a view from the dom. or events hash (or method) can be used to specify a set of DOM events that will be bound to methods on your View through delegateEvents.
delegateEventsdelegateEvents([events])It binds elements to the specified DOM elements with callback methods to handle events.
undelegateEventsundelegateEvents()Removes all of the view’s delegated events. Useful if you want to disable or remove a view from the DOM temporarily.