No suitable constructor exists to convert from là gì năm 2024

Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.

The project is hosted on GitHub, and the annotated source code is available, as well as an online test suite, an example application, a list of tutorials and a that use Backbone. Backbone is available for use under the MIT software license.

You can report bugs and discuss features on the GitHub issues page, or add pages to the wiki.

Backbone is an open-source component of DocumentCloud.

Downloads & Dependencies[Right-click, and use "Save As"]

Backbone's only hard dependency is Underscore.js [ >= 1.8.3]. For RESTful persistence and DOM manipulation with , include jQuery [ >= 1.11.0]. [Mimics of the Underscore and jQuery APIs, such as Lodash and Zepto, will also tend to work, with varying degrees of compatibility.]

Getting Started

When working on a web application that involves a lot of JavaScript, one of the first things you learn is to stop tying your data to the DOM. It's all too easy to create JavaScript applications that end up as tangled piles of jQuery selectors and callbacks, all trying frantically to keep data in sync between the HTML UI, your JavaScript logic, and the database on your server. For rich client-side applications, a more structured approach is often helpful.

With Backbone, you represent your data as , which can be created, validated, destroyed, and saved to the server. Whenever a UI action causes an attribute of a model to change, the model triggers a "change" event; all the that display the model's state can be notified of the change, so that they are able to respond accordingly, re-rendering themselves with the new information. In a finished Backbone app, you don't have to write the glue code that looks into the DOM to find an element with a specific id, and update the HTML manually — when the model changes, the views simply update themselves.

Philosophically, Backbone is an attempt to discover the minimal set of data-structuring [models and collections] and user interface [views and URLs] primitives that are generally useful when building web applications with JavaScript. In an ecosystem where overarching, decides-everything-for-you frameworks are commonplace, and many libraries require your site to be reorganized to suit their look, feel, and default behavior — Backbone should continue to be a tool that gives you the freedom to design the full experience of your web application.

If you're new here, and aren't yet quite sure what Backbone is for, start by browsing the .

Many of the code examples in this documentation are runnable, because Backbone is included on this page. Click the play button to execute them.

Models and Views

The single most important thing that Backbone can help you with is keeping your business logic separate from your user interface. When the two are entangled, change is hard; when logic doesn't depend on UI, your interface becomes easier to work with.

Model

  • Orchestrates data and business logic.
  • Loads and saves data from the server.
  • Emits events when data changes.

View

  • Listens for changes and renders UI.
  • Handles user input and interactivity.
  • Sends captured input to the model.

A Model manages an internal table of data attributes, and triggers "change" events when any of its data is modified. Models handle syncing data with a persistence layer — usually a REST API with a backing database. Design your models as the atomic reusable objects containing all of the helpful functions for manipulating their particular bit of data. Models should be able to be passed around throughout your app, and used anywhere that bit of data is needed.

A View is an atomic chunk of user interface. It often renders the data from a specific model, or number of models — but views can also be data-less chunks of UI that stand alone. Models should be generally unaware of views. Instead, views listen to the model "change" events, and react or re-render themselves appropriately.

Collections

A Collection helps you deal with a group of related models, handling the loading and saving of new models to the server and providing helper functions for performing aggregations or computations against a list of models. Aside from their own events, collections also proxy through all of the events that occur to models within them, allowing you to listen in one place for any change that might happen to any model in the collection.

API Integration

Backbone is pre-configured to sync with a RESTful API. Simply create a new Collection with the url of your resource endpoint:

var Books = Backbone.Collection.extend[{ url: '/books' }];

The Collection and Model components together form a direct mapping of REST resources using the following methods:

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

When fetching raw JSON data from an API, a Collection will automatically populate itself with data formatted as an array, while a Model will automatically populate itself with data formatted as an object:

[{"id": 1}] ..... populates a Collection with one model. {"id": 1} ....... populates a Model with one attribute.

However, it's fairly common to encounter APIs that return data in a different format than what Backbone expects. For example, consider fetching a Collection from an API that returns the real data array wrapped in metadata:

{ "page": 1, "limit": 10, "total": 2, "books": [

{"id": 1, "title": "Pride and Prejudice"},
{"id": 4, "title": "The Great Gatsby"}
] }

In the above example data, a Collection should populate using the "books" array rather than the root object structure. This difference is easily reconciled using a parse method that returns [or transforms] the desired portion of API data:

var Books = Backbone.Collection.extend[{ url: '/books', parse: function[data] {

return data.books;
} }];

View Rendering

Each View manages the rendering and user interaction within its own DOM element. If you're strict about not allowing views to reach outside of themselves, it helps keep your interface flexible — allowing views to be rendered in isolation in any place where they might be needed.

Backbone remains unopinionated about the process used to render View objects and their subviews into UI: you define how your models get translated into HTML [or SVG, or Canvas, or something even more exotic]. It could be as prosaic as a simple , or as fancy as the React virtual DOM. Some basic approaches to rendering views can be found in the Backbone primer.

Routing with URLs

In rich web applications, we still want to provide linkable, bookmarkable, and shareable URLs to meaningful locations within an app. Use the Router to update the browser URL whenever the user reaches a new "place" in your app that they might want to bookmark or share. Conversely, the Router detects changes to the URL — say, pressing the "Back" button — and can tell your application exactly where you are now.

Backbone.Events

Events is a module that can be mixed in to any object, giving the object the ability to bind and trigger custom named events. Events do not have to be declared before they are bound, and may take passed arguments. For example:

var object = {}; _.extend[object, Backbone.Events]; object.on["alert", function[msg] { alert["Triggered " + msg]; }]; object.trigger["alert", "an event"];

For example, to make a handy event dispatcher that can coordinate events among different areas of your application: var dispatcher = _.clone[Backbone.Events]

book.on[{ "change:author": authorPane.update, "change:title change:subtitle": titleView.update, "destroy": bookView.remove }];

3Alias: bind Bind a callback function to an object. The callback will be invoked whenever the event is fired. If you have a large number of different events on a page, the convention is to use colons to namespace them: "poll:start", or "change:selection". The event string may also be a space-delimited list of several events...

book.on["change:title change:author", ...];

Callbacks bound to the special "all" event will be triggered when any event occurs, and are passed the name of the event as the first argument. For example, to proxy all events from one object to another:

proxy.on["all", function[eventName] { object.trigger[eventName]; }];

All Backbone event methods also support an event map syntax, as an alternative to positional arguments:

book.on[{ "change:author": authorPane.update, "change:title change:subtitle": titleView.update, "destroy": bookView.remove }];

To supply a context value for this when the callback is invoked, pass the optional last argument: model.on['change', this.render, this] or model.on[{change: this.render}, this].

book.on[{ "change:author": authorPane.update, "change:title change:subtitle": titleView.update, "destroy": bookView.remove }];

4Alias: unbind Remove a previously-bound callback function from an object. If no context is specified, all of the versions of the callback with different contexts will be removed. If no callback is specified, all callbacks for the event will be removed. If no event is specified, callbacks for all events will be removed.

// Removes just the onChange callback. object.off["change", onChange]; // Removes all "change" callbacks. object.off["change"]; // Removes the onChange callback for all events. object.off[null, onChange]; // Removes all callbacks for context for all events. object.off[null, null, context]; // Removes all callbacks on object. object.off[];

Note that calling model.off[], for example, will indeed remove all events on the model — including events that Backbone uses for internal bookkeeping.

book.on[{ "change:author": authorPane.update, "change:title change:subtitle": titleView.update, "destroy": bookView.remove }];

5 Trigger callbacks for the given event, or space-delimited list of events. Subsequent arguments to trigger will be passed along to the event callbacks.

book.on[{ "change:author": authorPane.update, "change:title change:subtitle": titleView.update, "destroy": bookView.remove }];

6 Just like , but causes the bound callback to fire only once before being removed. Handy for saying "the next time that X happens, do this". When multiple events are passed in using the space separated syntax, the event will fire once for every event you passed in, not once for a combination of all events

book.on[{ "change:author": authorPane.update, "change:title change:subtitle": titleView.update, "destroy": bookView.remove }];

7 Tell an object to listen to a particular event on an other object. The advantage of using this form, instead of other.on[event, callback, object], is that listenTo allows the object to keep track of the events, and they can be removed all at once later on. The callback will always be called with object as context.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

0

book.on[{ "change:author": authorPane.update, "change:title change:subtitle": titleView.update, "destroy": bookView.remove }];

8 Tell an object to stop listening to events. Either call stopListening with no arguments to have the object remove all of its callbacks ... or be more precise by telling it to remove just the events it's listening to on a specific object, or a specific event, or just a specific callback.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

1

book.on[{ "change:author": authorPane.update, "change:title change:subtitle": titleView.update, "destroy": bookView.remove }];

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

Here's the complete list of built-in Backbone events, with arguments. You're also free to trigger your own events on Models, Collections and Views as you see fit. The Backbone object itself mixes in Events, and can be used to emit any global events that your application needs.

  • "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 .
  • "sort" [collection, options] — when the collection has been re-sorted.
  • "change" [model, options] — when a model's attributes have changed.
  • "changeId" [model, previousId, options] — when the model's id has been updated.
  • "change:[attribute]" [model, value, options] — when a specific attribute has been updated.
  • "destroy" [model, collection, options] — when a model is .
  • "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 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.
  • "notfound" [] — Fired by history when no route could be matched.
  • "all" — this special event fires for any triggered event, passing the event name as the first argument followed by all trigger arguments.

Generally speaking, when calling a function that emits an event [model.set, collection.add, and so on...], if you'd like to prevent the event from being triggered, you may pass {silent: true} as an option. Note that this is rarely, perhaps even never, a good idea. Passing through a specific flag in the options for your event callback to look at, and choose to ignore, will usually work out better.

Backbone.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. You extend Backbone.Model with your domain-specific methods, and Model provides a basic set of functionality for managing changes.

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.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

2

// Removes just the onChange callback. object.off["change", onChange]; // Removes all "change" callbacks. object.off["change"]; // Removes the onChange callback for all events. object.off[null, onChange]; // Removes all callbacks for context for all events. object.off[null, null, context]; // Removes all callbacks on object. object.off[];

0 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.

extend correctly sets up the prototype chain, so subclasses created with extend can be further extended and subclassed as far as you like.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

3

Brief aside on super: JavaScript does not provide a simple way to call super — the function of the same name defined higher on the prototype chain. If you override a core function like set, or save, and you want to invoke the parent object's implementation, you'll have to explicitly call it, along these lines:

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

4

// Removes just the onChange callback. object.off["change", onChange]; // Removes all "change" callbacks. object.off["change"]; // Removes the onChange callback for all events. object.off[null, onChange]; // Removes all callbacks for context for all events. object.off[null, null, context]; // Removes all callbacks on object. object.off[];

1 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.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

5

// Removes just the onChange callback. object.off["change", onChange]; // Removes all "change" callbacks. object.off["change"]; // Removes the onChange callback for all events. object.off[null, onChange]; // Removes all callbacks for context for all events. object.off[null, null, context]; // Removes all callbacks on object. object.off[];

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

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

6

In rare cases, 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.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

7

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 . 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 before being on the model.

// Removes just the onChange callback. object.off["change", onChange]; // Removes all "change" callbacks. object.off["change"]; // Removes the onChange callback for all events. object.off[null, onChange]; // Removes all callbacks for context for all events. object.off[null, null, context]; // Removes all callbacks on object. object.off[];

3 Get the current value of an attribute from the model. For example: note.get["title"]

// Removes just the onChange callback. object.off["change", onChange]; // Removes all "change" callbacks. object.off["change"]; // Removes the onChange callback for all events. object.off[null, onChange]; // Removes all callbacks for context for all events. object.off[null, null, context]; // Removes all callbacks on object. object.off[];

4 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.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

8

// Removes just the onChange callback. object.off["change", onChange]; // Removes all "change" callbacks. object.off["change"]; // Removes the onChange callback for all events. object.off[null, onChange]; // Removes all callbacks for context for all events. object.off[null, null, context]; // Removes all callbacks on object. object.off[];

5 Similar to , 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.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

9

// Removes just the onChange callback. object.off["change", onChange]; // Removes all "change" callbacks. object.off["change"]; // Removes the onChange callback for all events. object.off[null, onChange]; // Removes all callbacks for context for all events. object.off[null, null, context]; // Removes all callbacks on object. object.off[];

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

[{"id": 1}] ..... populates a Collection with one model. {"id": 1} ....... populates a Model with one attribute.

0

// Removes just the onChange callback. object.off["change", onChange]; // Removes all "change" callbacks. object.off["change"]; // Removes the onChange callback for all events. object.off[null, onChange]; // Removes all callbacks for context for all events. object.off[null, null, context]; // Removes all callbacks on object. object.off[];

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

// Removes just the onChange callback. object.off["change", onChange]; // Removes all "change" callbacks. object.off["change"]; // Removes the onChange callback for all events. object.off[null, onChange]; // Removes all callbacks for context for all events. object.off[null, null, context]; // Removes all callbacks on object. object.off[];

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

// Removes just the onChange callback. object.off["change", onChange]; // Removes all "change" callbacks. object.off["change"]; // Removes the onChange callback for all events. object.off[null, onChange]; // Removes all callbacks for context for all events. object.off[null, null, context]; // Removes all callbacks on object. object.off[];

9 A 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.

// Removes just the onChange callback. object.off["change", onChange]; // Removes all "change" callbacks. object.off["change"]; // Removes the onChange callback for all events. object.off[null, onChange]; // Removes all callbacks for context for all events. object.off[null, null, context]; // Removes all callbacks on object. object.off[];

9 should not be manipulated directly, it should be modified only via

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

01. Models can be retrieved by id from collections, and the id is used to generate model URLs by default.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

02 A model's unique identifier is stored under the id attribute. If you're directly communicating with a backend [CouchDB, MongoDB] that uses a different unique key, you may set a Model's idAttribute to transparently map from that key to id. If you set idAttribute, you may also want to override .

[{"id": 1}] ..... populates a Collection with one model. {"id": 1} ....... populates a Model with one attribute.

1

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

03 A special property of models, the cid or client id is a unique identifier automatically assigned to all models when they're first created. Client ids are handy when the model has not yet been saved to the server, and does not yet have its eventual true id, but already needs to be visible in the UI.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

04 If your model has an id that is anything other than an integer or a UUID, there is the possibility that it might collide with its cid. To prevent this, you can override the prefix that cids start with.

[{"id": 1}] ..... populates a Collection with one model. {"id": 1} ....... populates a Model with one attribute.

2

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

05 The attributes property is the internal hash containing the model's state — usually [but not necessarily] a form of the JSON object representing the model data on the server. It's often a straightforward serialization of a row from the database, but it could also be client-side computed state.

Please use to update the attributes instead of modifying them directly. If you'd like to retrieve and munge a copy of the model's attributes, use _.clone[model.attributes] instead.

Due to the fact that accepts space separated lists of events, attribute names should not include spaces.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

06 The changed property is the internal hash containing all the attributes that have changed since its last . Please do not update changed directly since its state is internally maintained by . A copy of changed can be acquired from .

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

07 The defaults hash [or function] can be used to specify the default attributes for your model. When creating an instance of the model, any unspecified attributes will be set to their default value.

[{"id": 1}] ..... populates a Collection with one model. {"id": 1} ....... populates a Model with one attribute.

3

Remember that in JavaScript, objects are passed by reference, so if you include an object as a default value, it will be shared among all instances. Instead, define defaults as a function.

If you set a value for the model’s , you should define the defaults as a function that returns a different, universally unique id on every invocation. Not doing so would likely prevent an instance of Backbone.Collection from correctly identifying model hashes and is almost certainly a mistake, unless you never add instances of the model class to a collection.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

08 Return a shallow copy of the model's 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 works.

[{"id": 1}] ..... populates a Collection with one model. {"id": 1} ....... populates a Model with one attribute.

4

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

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

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

10 Merges the model's state with attributes fetched from the server by delegating to . Returns a . 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.

[{"id": 1}] ..... populates a Collection with one model. {"id": 1} ....... populates a Model with one attribute.

5

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

11 Save a model to your database [or alternative persistence layer], by delegating to . Returns a if validation is successful and false otherwise. The attributes hash [as in ] 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 method, and validation fails, the model will not be saved. If the model , 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.

[{"id": 1}] ..... populates a Collection with one model. {"id": 1} ....... populates a Model with one attribute.

6

save accepts success and error callbacks in the options hash, which will be passed the arguments [model, response, options]. If a server-side validation fails, return a non-200 HTTP response code, along with an error response in text or JSON.

[{"id": 1}] ..... populates a Collection with one model. {"id": 1} ....... populates a Model with one attribute.

7

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

12 Destroys the model on the server by delegating an HTTP DELETE request to . Returns a object, or false if the model . 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.

[{"id": 1}] ..... populates a Collection with one model. {"id": 1} ....... populates a Model with one attribute.

8

Backbone proxies to Underscore.js to provide 9 object functions on Backbone.Model. They aren't all documented here, but you can take a look at the Underscore documentation for the full details…

[{"id": 1}] ..... populates a Collection with one model. {"id": 1} ....... populates a Model with one attribute.

9

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

13 This method is left undefined and you're encouraged to override it with any custom validation logic you have that can be performed in JavaScript. If the attributes are valid, don't return anything from validate; if they are invalid return an error of your choosing. It can be as simple as a string error message to be displayed, or a complete error object that describes the error programmatically.

By default save checks validate before setting any attributes but you may also tell set to validate the new attributes by passing {validate: true} as an option. The validate method receives the model attributes as well as any options passed to set or save, if validate returns an error, save does not continue, the model attributes are not modified on the server, an "invalid" event is triggered, and the validationError property is set on the model with the value returned by this method.

{ "page": 1, "limit": 10, "total": 2, "books": [

{"id": 1, "title": "Pride and Prejudice"},
{"id": 4, "title": "The Great Gatsby"}
] }

0

"invalid" events are useful for providing coarse-grained error messages at the model or collection level.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

14 The value returned by during the last failed validation.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

15 Run to check the model state.

The validate method receives the model attributes as well as any options passed to isValid, if validate returns an error an "invalid" event is triggered, and the error is set on the model in the validationError property.

{ "page": 1, "limit": 10, "total": 2, "books": [

{"id": 1, "title": "Pride and Prejudice"},
{"id": 4, "title": "The Great Gatsby"}
] }

1

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

16 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 to generate the URL, so make sure that you have it defined, or a property, if all models of this class share a common root URL. A model with an id of 101, stored in a with a url of "/documents/7/notes", would have this URL: "/documents/7/notes/101"

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

17 Specify a urlRoot if you're using a model outside of a collection, to enable the default function to generate URLs based on the model id. "[urlRoot]/id" Normally, you won't need to define this. Note that urlRoot may also be a function.

{ "page": 1, "limit": 10, "total": 2, "books": [

{"id": 1, "title": "Pride and Prejudice"},
{"id": 4, "title": "The Great Gatsby"}
] }

2

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

18 parse is called whenever a model's data is returned by the server, in , and . The function is passed the raw response object, and should return the attributes hash to be 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.

If you're working with a Rails backend that has a version prior to 3.1, you'll notice that its default to_json implementation includes a model's attributes under a namespace. To disable this behavior for seamless Backbone integration, set:

{ "page": 1, "limit": 10, "total": 2, "books": [

{"id": 1, "title": "Pride and Prejudice"},
{"id": 4, "title": "The Great Gatsby"}
] }

3

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

19 Returns a new instance of the model with identical attributes.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

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

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

21 Has the model changed since its last ? 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.

{ "page": 1, "limit": 10, "total": 2, "books": [

{"id": 1, "title": "Pride and Prejudice"},
{"id": 4, "title": "The Great Gatsby"}
] }

4

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

22 Retrieve a hash of only the model's attributes that have changed since the last , 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.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

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

{ "page": 1, "limit": 10, "total": 2, "books": [

{"id": 1, "title": "Pride and Prejudice"},
{"id": 4, "title": "The Great Gatsby"}
] }

5

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

24 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.Collection

Collections are ordered sets of models. You can bind "change" events to be notified when any model in the collection has been modified, listen for "add" and "remove" events, fetch the collection from the server, and use a full suite of .

Any event that is triggered on a model in a collection will also be triggered on the collection directly, for convenience. This allows you to listen for changes to specific attributes in any model in a collection, for example: documents.on["change:selected", ...]

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

25 To create a Collection class of your own, extend Backbone.Collection, providing instance properties, as well as optional classProperties to be attached directly to the collection's constructor function.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

26 Override this property to specify the model class that the collection contains. If defined, you can pass raw attributes objects [and arrays] and options to , , and , and the attributes will be converted into a model of the proper type using the provided options, if any.

{ "page": 1, "limit": 10, "total": 2, "books": [

{"id": 1, "title": "Pride and Prejudice"},
{"id": 4, "title": "The Great Gatsby"}
] }

6

A collection can also contain polymorphic models by overriding this property with a constructor that returns a model.

{ "page": 1, "limit": 10, "total": 2, "books": [

{"id": 1, "title": "Pride and Prejudice"},
{"id": 4, "title": "The Great Gatsby"}
] }

7

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

27 Override this method to return the value the collection will use to identify a model given its attributes. Useful for combining models from multiple tables with different values into a single collection.

By default returns the value of the given within the attrs, or failing that, id. If your collection uses a and the id ranges of those models might collide, you must override this method.

{ "page": 1, "limit": 10, "total": 2, "books": [

{"id": 1, "title": "Pride and Prejudice"},
{"id": 4, "title": "The Great Gatsby"}
] }

8

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

28 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.

{ "page": 1, "limit": 10, "total": 2, "books": [

{"id": 1, "title": "Pride and Prejudice"},
{"id": 4, "title": "The Great Gatsby"}
] }

9

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

28 When creating a Collection, you may choose to pass in the initial array of models. The collection's may be included as an option. Passing false as the comparator option will prevent sorting. If you define an initialize function, it will be invoked when the collection is created. There are a couple of options that, if provided, are attached to the collection directly: model and comparator. Pass null for models to create an empty Collection with options.

var Books = Backbone.Collection.extend[{ url: '/books', parse: function[data] {

return data.books;
} }];

0

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

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

30 Raw access to the JavaScript array of models inside of the collection. Usually you'll want to use get, at, or the Underscore methods to access model objects, but occasionally a direct reference to the array is desired.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

31 Return an array containing the attributes hash of each model [via ] in the collection. This can be used to serialize and persist the collection as a whole. The name of this method is a bit confusing, because it conforms to .

var Books = Backbone.Collection.extend[{ url: '/books', parse: function[data] {

return data.books;
} }];

1

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

32 Uses to persist the state of a collection to the server. Can be overridden for custom behavior.

Backbone proxies to Underscore.js to provide 46 iteration functions on Backbone.Collection. They aren't all documented here, but you can take a look at the Underscore documentation for the full details…

Most methods can take an object or string to support model-attribute-style predicates or a function that receives the model instance as an argument.

var Books = Backbone.Collection.extend[{ url: '/books', parse: function[data] {

return data.books;
} }];

2

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

33 Add a model [or an array of models] to the collection, firing an "add" event for each model, and an "update" event afterwards. This is a variant of with the same options and return value, but it always adds and never removes. If you're adding models to the collection that are already in the collection, they'll be ignored, unless you pass {merge: true}, in which case their attributes will be merged into the corresponding models, firing any appropriate "change" events.

var Books = Backbone.Collection.extend[{ url: '/books', parse: function[data] {

return data.books;
} }];

3

Note that adding the same model [a model with the same id] to a collection more than once is a no-op.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

34 Remove a model [or an array of models] from the collection, and return them. Each model can be a Model instance, an id string or a JS object, any value acceptable as the id argument of . Fires a "remove" event for each model, and a single "update" event afterwards, unless {silent: true} is passed. The model's index before removal is available to listeners as options.index.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

35 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. Use reset to replace a collection with a new list of models [or attribute hashes], triggering a single "reset" event on completion, and without triggering any add or remove events on any models. Returns the newly-set models. For convenience, within a "reset" event, the list of any previous models is available as options.previousModels. Pass null for models to empty your Collection with options.

Here's an example using reset to bootstrap a collection during initial page load, in a Rails application:

var Books = Backbone.Collection.extend[{ url: '/books', parse: function[data] {

return data.books;
} }];

4

Calling collection.reset[] without passing any models as arguments will empty the entire collection.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

36 The set method performs a "smart" update of the collection with the passed list of models. If a model in the list isn't yet in the collection it will be added; if the model is already in the collection its attributes will be merged; and if the collection contains any models that aren't present in the list, they'll be removed. All of the appropriate "add", "remove", and "change" events are fired as this happens, with a single "update" event at the end. Returns the touched models in the collection. If you'd like to customize this behavior, you can change it with options: {add: false}, {remove: false}, or {merge: false}.

If a property is defined, you may also pass raw attributes objects and options, and have them be vivified as instances of the model using the provided options. If you set a , the collection will automatically sort itself and trigger a "sort" event, unless you pass {sort: false} or use the {at: index} option. Pass {at: index} to splice the model[s] into the collection at the specified index.

var Books = Backbone.Collection.extend[{ url: '/books', parse: function[data] {

return data.books;
} }];

5

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

37 Get a model from a collection, specified by an , a , or by passing in a model.

var Books = Backbone.Collection.extend[{ url: '/books', parse: function[data] {

return data.books;
} }];

6

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

38 Get a model from a collection, specified by index. Useful if your collection is sorted, and if your collection isn't sorted, at will still retrieve models in insertion order. When passed a negative index, it will retrieve the model from the back of the collection.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

39 Like , but always adds a model at the end of the collection and never sorts.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

40 Remove and return the last model from a collection. Takes the same options as .

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

41 Like , but always adds a model at the beginning of the collection and never sorts.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

42 Remove and return the first model from a collection. Takes the same options as .

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

43 Return a shallow copy of this collection's models, using the same options as native Array

slice.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

44 Like an array, a Collection maintains a length property, counting the number of models it contains.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

45 By default there is no comparator for a collection. If you define a comparator, it will be used to sort the collection any time a model is added. A comparator can be defined as a [pass a function that takes a single argument], as a sort [pass a comparator function that expects two arguments], or as a string indicating the attribute to sort by.

"sortBy" comparator functions take a model and return a numeric or string value by which the model should be ordered relative to others. "sort" comparator functions take two models, and return -1 if the first model should come before the second, 0 if they are of the same rank and 1 if the first model should come after. Note that Backbone depends on the arity of your comparator function to determine between the two styles, so be careful if your comparator function is bound.

Note how even though all of the chapters in this example are added backwards, they come out in the proper order:

var Books = Backbone.Collection.extend[{ url: '/books', parse: function[data] {

return data.books;
} }];

7

Collections with a comparator will not automatically re-sort if you later change model attributes, so you may wish to call sort after changing model attributes that would affect the order.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

46 Force a collection to re-sort itself. Note that a collection with a will sort itself automatically whenever a model is added. To disable sorting when adding a model, pass {sort: false} to add. Calling sort triggers a "sort" event on the collection.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

47 Pluck an attribute from each model in the collection. Equivalent to calling map and returning a single attribute from the iterator.

var Books = Backbone.Collection.extend[{ url: '/books', parse: function[data] {

return data.books;
} }];

8

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

48 Return an array of all the models in a collection that match the passed attributes. Useful for simple cases of filter.

var Books = Backbone.Collection.extend[{ url: '/books', parse: function[data] {

return data.books;
} }];

9

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

49 Just like , but directly returns only the first model in the collection that matches the passed attributes. If no model matches returns undefined.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

50 Set the url property [or function] on a collection to reference its location on the server. Models within the collection will use url to construct URLs of their own.

var object = {}; _.extend[object, Backbone.Events]; object.on["alert", function[msg] { alert["Triggered " + msg]; }]; object.trigger["alert", "an event"];

0

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

51 parse is called by Backbone whenever a collection's models are returned by the server, in . The function is passed the raw response object, and should return the array of model attributes to be to the collection. 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.

var object = {}; _.extend[object, Backbone.Events]; object.on["alert", function[msg] { alert["Triggered " + msg]; }]; object.trigger["alert", "an event"];

1

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

52 Returns a new instance of the collection with an identical list of models.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

53 Fetch the default set of models for this collection from the server, them on the collection when they arrive. The options hash takes success and error callbacks which will both be passed [collection, response, options] as arguments. When the model data returns from the server, it uses to [intelligently] merge the fetched models, unless you pass {reset: true}, in which case the collection will be [efficiently] . Delegates to under the covers for custom persistence strategies and returns a . The server handler for fetch requests should return a JSON array of models.

var object = {}; _.extend[object, Backbone.Events]; object.on["alert", function[msg] { alert["Triggered " + msg]; }]; object.trigger["alert", "an event"];

2

The behavior of fetch can be customized by using the available options. For example, to fetch a collection, getting an "add" event for every new model, and a "change" event for every changed existing model, without removing anything: collection.fetch[{remove: false}]

jQuery.ajax options can also be passed directly as fetch options, so to fetch a specific page of a paginated collection: Documents.fetch[{data: {page: 3}}]

Note that fetch should not be used to populate collections on page load — all models needed at load time should already be in to place. fetch is intended for lazily-loading models for interfaces that are not needed immediately: for example, documents with collections of notes that may be toggled open and closed.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

54 Convenience to create a new instance of a model within a collection. Equivalent to instantiating a model with a hash of attributes, saving the model to the server, and adding the model to the set after being successfully created. Returns the new model. If client-side validation failed, the model will be unsaved, with validation errors. In order for this to work, you should set the property of the collection. The create method can accept either an attributes hash and options to be passed down during model instantiation or an existing, unsaved model object.

Creating a model will cause an immediate "add" event to be triggered on the collection, a "request" event as the new model is sent to the server, as well as a "sync" event, once the server has responded with the successful creation of the model. Pass {wait: true} if you'd like to wait for the server before adding the new model to the collection.

var object = {}; _.extend[object, Backbone.Events]; object.on["alert", function[msg] { alert["Triggered " + msg]; }]; object.trigger["alert", "an event"];

3

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

55

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

56 provides a way to enhance the base Backbone.Collection and any collections which extend it. This can be used to add generic methods [e.g. additional ].

var object = {}; _.extend[object, Backbone.Events]; object.on["alert", function[msg] { alert["Triggered " + msg]; }]; object.trigger["alert", "an event"];

4

Backbone.Router

Web applications often provide linkable, bookmarkable, shareable URLs for important locations in the app. Until recently, hash fragments [

page] were used to provide these permalinks, but with the arrival of the History API, it's now possible to use standard URLs [/page]. Backbone.Router provides methods for routing client-side pages, and connecting them to actions and events. For browsers which don't yet support the History API, the Router handles graceful fallback and transparent translation to the fragment version of the URL.

During page load, after your application has finished creating all of its routers, be sure to call Backbone.history.start[] or Backbone.history.start[{pushState: true}] to route the initial URL.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

57 Get started by creating a custom router class. Define action functions that are triggered when certain URL fragments are matched, and provide a hash that pairs routes to actions. Note that you'll want to avoid using a leading slash in your route definitions:

var object = {}; _.extend[object, Backbone.Events]; object.on["alert", function[msg] { alert["Triggered " + msg]; }]; object.trigger["alert", "an event"];

5

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

58 The routes hash maps URLs with parameters to functions on your router [or just direct function definitions, if you prefer], similar to the 's . Routes can contain parameter parts, :param, which match a single URL component between slashes; and splat parts *splat, which can match any number of URL components. Part of a route can be made optional by surrounding it in parentheses [/:optional].

For example, a route of "search/:query/p:page" will match a fragment of

search/obama/p2, passing "obama" and "2" to the action as positional arguments.

A route of "file/*path" will match

file/folder/file.txt, passing "folder/file.txt" to the action.

A route of "docs/:section[/:subsection]" will match

docs/faq and

docs/faq/installing, passing "faq" to the action in the first case, and passing "faq" and "installing" to the action in the second.

A nested optional route of "docs[/:section][/:subsection]" will match

docs,

docs/faq, and

docs/faq/installing, passing "faq" to the action in the second case, and passing "faq" and "installing" to the action in the third.

Trailing slashes are treated as part of the URL, and [correctly] treated as a unique route when accessed. docs and docs/ will fire different callbacks. If you can't avoid generating both types of URLs, you can define a "docs[/]" matcher to capture both cases.

When the visitor presses the back button, or enters a URL, and a particular route is matched, the name of the action will be fired as an , so that other objects can listen to the router, and be notified. In the following example, visiting

help/uploading will fire a route:help event from the router.

var object = {}; _.extend[object, Backbone.Events]; object.on["alert", function[msg] { alert["Triggered " + msg]; }]; object.trigger["alert", "an event"];

6

var object = {}; _.extend[object, Backbone.Events]; object.on["alert", function[msg] { alert["Triggered " + msg]; }]; object.trigger["alert", "an event"];

7

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

59 For use with routers as ES classes. If you define a preinitialize method, it will be invoked when the Router is first created and before any instantiation logic is run for the Router.

var object = {}; _.extend[object, Backbone.Events]; object.on["alert", function[msg] { alert["Triggered " + msg]; }]; object.trigger["alert", "an event"];

8

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

60 When creating a new router, you may pass its hash directly as an option, if you choose. All options will also be passed to your initialize function, if defined.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

61 Manually create a route for the router, The route argument may be a or regular expression. Each matching capture from the route or regular expression will be passed as an argument to the callback. The name argument will be triggered as a "route:name" event whenever the route is matched. If the callback argument is omitted router[name] will be used instead. Routes added later may override previously declared routes.

var object = {}; _.extend[object, Backbone.Events]; object.on["alert", function[msg] { alert["Triggered " + msg]; }]; object.trigger["alert", "an event"];

9

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

62 Whenever you reach a point in your application that you'd like to save as a URL, call navigate in order to update the URL. If you also wish to call the route function, set the trigger option to true. To update the URL without creating an entry in the browser's history, set the replace option to true.

book.on["change:title change:author", ...];

0

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

63 This method is called internally within the router, whenever a route matches and its corresponding callback is about to be executed. Return false from execute to cancel the current transition. Override it to perform custom parsing or wrapping of your routes, for example, to parse query strings before handing them to your route callback, like so:

book.on["change:title change:author", ...];

1

Backbone.history

History serves as a global router [per frame] to handle hashchange events or pushState, match the appropriate route, and trigger callbacks. It forwards the "route" and "route[name]" events of the matching router, or "notfound" when no route in any router matches the current URL. You shouldn't ever have to create one of these yourself since Backbone.history already contains one.

pushState support exists on a purely opt-in basis in Backbone. Older browsers that don't support pushState will continue to use hash-based URL fragments, and if a hash URL is visited by a pushState-capable browser, it will be transparently upgraded to the true URL. Note that using real URLs requires your web server to be able to correctly render those pages, so back-end changes are required as well. For example, if you have a route of /documents/100, your web server must be able to serve that page, if the browser visits that URL directly. For full search-engine crawlability, it's best to have the server generate the complete HTML for the page ... but if it's a web application, just rendering the same content you would have for the root URL, and filling in the rest with Backbone Views and JavaScript works fine.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

64 When all of your have been created, and all of the routes are set up properly, call Backbone.history.start[] to begin monitoring hashchange events, and dispatching routes. Subsequent calls to Backbone.history.start[] will throw an error, and Backbone.History.started is a boolean value indicating whether it has already been called.

To indicate that you'd like to use HTML5 pushState support in your application, use Backbone.history.start[{pushState: true}]. If you'd like to use pushState, but have browsers that don't support it natively use full page refreshes instead, you can add {hashChange: false} to the options.

If your application is not being served from the root url / of your domain, be sure to tell History where the root really is, as an option: Backbone.history.start[{pushState: true, root: "/public/search/"}].

The value provided for root will be normalized to include a leading and trailing slash. When navigating to a route the default behavior is to exclude the trailing slash from the URL [e.g., /public/search?query=...]. If you prefer to include the trailing slash [e.g., /public/search/?query=...] use Backbone.history.start[{trailingSlash: true}]. URLs will always contain a leading slash. When root is / URLs will look like /?query=... regardless of the value of trailingSlash.

When called, if a route succeeds with a match for the current URL, Backbone.history.start[] returns true and the "route" and "route[name]" events are triggered. If no defined route matches the current URL, it returns false and "notfound" is triggered instead.

If the server has already rendered the entire page, and you don't want the initial route to trigger when starting History, pass silent: true.

Because hash-based history in Internet Explorer relies on an , be sure to call start[] only after the DOM is ready.

book.on["change:title change:author", ...];

2

Backbone.sync

Backbone.sync is the function that Backbone calls every time it attempts to read or save a model to the server. By default, it uses jQuery.ajax to make a RESTful JSON request and returns a . You can override it in order to use a different persistence strategy, such as WebSockets, XML transport, or Local Storage.

The method signature of Backbone.sync is sync[method, model, [options]]

  • 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

With the default implementation, when Backbone.sync sends up a request to save a model, its attributes will be passed, serialized as JSON, and sent in the HTTP body with content-type application/json. When returning a JSON response, send down the attributes of the model that have been changed by the server, and need to be updated on the client. When responding to a "read" request from a collection [], send down an array of model attribute objects.

Whenever a model or collection begins a sync with the server, a "request" event is emitted. If the request completes successfully you'll get a "sync" event, and an "error" event if not.

The sync function may be overridden globally as Backbone.sync, or at a finer-grained level, by adding a sync function to a Backbone collection or to an individual model.

The default sync handler maps CRUD to REST like so:

  • create → POST /collection
  • read → GET /collection[/id]
  • update → PUT /collection/id
  • patch → PATCH /collection/id
  • delete → DELETE /collection/id

As an example, a Rails 4 handler responding to an "update" call from Backbone might look like this:

book.on["change:title change:author", ...];

3

One more tip for integrating Rails versions prior to 3.1 is to disable the default namespacing for to_json calls on models by setting ActiveRecord::Base.include_root_in_json = false

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

65 If you want to use a custom AJAX function, or your endpoint doesn't support the jQuery.ajax API and you need to tweak things, you can do so by setting Backbone.ajax.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

66 If you want to work with a legacy web server that doesn't support Backbone's default REST/HTTP approach, you may choose to turn on Backbone.emulateHTTP. Setting this option will fake PUT, PATCH and DELETE requests with a HTTP POST, setting the X-HTTP-Method-Override header with the true method. If emulateJSON is also on, the true method will be passed as an additional _method parameter.

book.on["change:title change:author", ...];

4

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

67 If you're working with a legacy web server that can't handle requests encoded as application/json, setting Backbone.emulateJSON = true; will cause the JSON to be serialized under a model parameter, and the request to be made with a application/x-www-form-urlencoded MIME type, as if from an HTML form.

Backbone.View

Backbone views are almost more convention than they are code — they don't determine anything about your HTML or CSS for you, and can be used with any JavaScript templating library. The general idea is to organize your interface into logical views, backed by models, each of which can be updated independently when the model changes, without having to redraw the page. Instead of digging into a JSON object, looking up an element in the DOM, and updating the HTML by hand, you can bind your view's render function to the model's "change" event — and now everywhere that model data is displayed in the UI, it is always immediately up to date.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

68 Get started with views by creating a custom view class. You'll want to override the function, specify your declarative , and perhaps the tagName, className, or id of the View's root element.

book.on["change:title change:author", ...];

5

Properties like tagName, id, className, el, and events may also be defined as a function, if you want to wait to define them until runtime.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

69 For use with views as ES classes. If you define a preinitialize method, it will be invoked when the view is first created, before any instantiation logic is run.

book.on["change:title change:author", ...];

6

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

69 There are several special options that, if passed, will be attached directly to the view: model, collection, el, id, className, tagName, attributes and events. If the view defines an initialize function, it will be called when the view is first created. If you'd like to create a view that references an element already in the DOM, pass in the element as an option: new View[{el: existingElement}]

book.on["change:title change:author", ...];

7

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

71 All views have a DOM element at all times [the el property], whether they've already been inserted into the page or not. In this fashion, views can be rendered at any time, and inserted into the DOM all at once, in order to get high-performance UI rendering with as few reflows and repaints as possible.

this.el can be resolved from a DOM selector string or an Element; otherwise it will be created from the view's tagName, className, id and properties. If none are set, this.el is an empty div, which is often just fine. An el reference may also be passed in to the view's constructor.

book.on["change:title change:author", ...];

8

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

72 A cached jQuery object for the view's element. A handy reference instead of re-wrapping the DOM element all the time.

book.on["change:title change:author", ...];

9

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

73 If you'd like to apply a Backbone view to a different DOM element, use setElement, which will also create the cached $el reference and move the view's delegated events from the old element to the new one.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

74 A hash of attributes that will be set as HTML DOM element attributes on the view's el [id, class, data-properties, etc.], or a function that returns such a hash.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

75 If jQuery is included on the page, each view has a $ function that runs queries scoped within the view's element. If you use this scoped jQuery function, you don't have to use model ids as part of your query to pull out specific elements in a list, and can rely much more on HTML class attributes. It's equivalent to running: view.$el.find[selector]

proxy.on["all", function[eventName] { object.trigger[eventName]; }];

0

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

76 While templating for a view isn't a function provided directly by Backbone, it's often a nice convention to define a template function on your views. In this way, when rendering your view, you have convenient access to instance data. For example, using Underscore templates:

proxy.on["all", function[eventName] { object.trigger[eventName]; }];

1

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

77 The default implementation of render is a no-op. Override this function with your code that renders the view template from model data, and updates this.el with the new HTML. A good convention is to return this at the end of render to enable chained calls.

proxy.on["all", function[eventName] { object.trigger[eventName]; }];

2

Backbone is agnostic with respect to your preferred method of HTML templating. Your render function could even munge together an HTML string, or use document.createElement to generate a DOM tree. However, we suggest choosing a nice JavaScript templating library. Mustache.js, Haml-js, and Eco are all fine alternatives. Because Underscore.js is already on the page, is available, and is an excellent choice if you prefer simple interpolated-JavaScript style templates.

Whatever templating strategy you end up with, it's nice if you never have to put strings of HTML in your JavaScript. At DocumentCloud, we use Jammit in order to package up JavaScript templates stored in /app/views as part of our main core.js asset package.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

78 Removes a view and its el from the DOM, and calls to remove any bound events that the view has 'd.

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

79 The events hash [or method] can be used to specify a set of DOM events that will be bound to methods on your View through .

Backbone will automatically attach the event listeners at instantiation time, right before invoking .

proxy.on["all", function[eventName] { object.trigger[eventName]; }];

3

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

80 Uses jQuery's on function to provide declarative callbacks for DOM events within a view. If an events hash is not passed directly, uses this.events as the source. Events are written in the format {"event selector": "callback"}. The callback may be either the name of a method on the view, or a direct function body. Omitting the selector causes the event to be bound to the view's root element [this.el]. By default, delegateEvents is called within the View's constructor for you, so if you have a simple events hash, all of your DOM events will always already be connected, and you will never have to call this function yourself.

The events property may also be defined as a function that returns an events hash, to make it easier to programmatically define your events, as well as inherit them from parent views.

Using delegateEvents provides a number of advantages over manually using jQuery to bind events to child elements during . All attached callbacks are bound to the view before being handed off to jQuery, so when the callbacks are invoked, this continues to refer to the view object. When delegateEvents is run again, perhaps with a different events hash, all callbacks are removed and delegated afresh — useful for views which need to behave differently when in different modes.

A single-event version of delegateEvents is available as delegate. In fact, delegateEvents is simply a multi-event wrapper around delegate. A counterpart to undelegateEvents is available as undelegate.

A view that displays a document in a search result might look something like this:

proxy.on["all", function[eventName] { object.trigger[eventName]; }];

4

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

81 Removes all of the view's delegated events. Useful if you want to disable or remove a view from the DOM temporarily.

Utility

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

82 Returns the Backbone object back to its original value. You can use the return value of Backbone.noConflict[] to keep a local reference to Backbone. Useful for embedding Backbone on third-party websites, where you don't want to clobber the existing Backbone.

proxy.on["all", function[eventName] { object.trigger[eventName]; }];

5

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

83 If you have multiple copies of jQuery on the page, or simply want to tell Backbone to use a particular object as its DOM / Ajax library, this is the property for you.

proxy.on["all", function[eventName] { object.trigger[eventName]; }];

6

GET /books/ .... collection.fetch[]; POST /books/ .... collection.create[]; GET /books/1 ... model.fetch[]; PUT /books/1 ... model.save[]; DEL /books/1 ... model.destroy[];

84 In the unfortunate event that you need to submit a bug report, this function makes it easier to provide detailed information about your setup. It prints a JSON object with version information about Backbone and its dependencies through console.debug. It also returns this object in case you want to inspect it in code.

debugInfo comes in a separate module that ships with the and releases later than 1.5.0. It is available in UMD format under the same prefix as backbone.js, but with debug-info.js as the file name. It is also experimentally available in ES module format under backbone/modules/.

proxy.on["all", function[eventName] { object.trigger[eventName]; }];

7

F.A.Q.

If your eye hasn't already been caught by the adaptability and elan on display in the above , we can get more specific: Backbone.js aims to provide the common foundation that data-rich web applications with ambitious interfaces require — while very deliberately avoiding painting you into a corner by making any decisions that you're better equipped to make yourself.

  • The focus is on supplying you with , not on HTML widgets or reinventing the JavaScript object model.
  • Backbone does not force you to use a single template engine. Views can bind to HTML constructed in favorite way.
  • It's smaller. There are fewer kilobytes for your browser or phone to download, and less conceptual surface area. You can read and understand the source in an afternoon.
  • It doesn't depend on stuffing application logic into your HTML. There's no embedded JavaScript, template logic, or binding hookup code in data- or ng- attributes, and no need to invent your own HTML tags.
  • are used as the fundamental building block, not a difficult-to-reason-about run loop, or by constantly polling and traversing your data structures to hunt for changes. And if you want a specific event to be asynchronous and aggregated, .
  • Backbone scales well, from embedded widgets to massive apps.
  • Backbone is a library, not a framework, and plays well with others. You can embed Backbone widgets in Dojo apps without trouble, or use Backbone models as the data backing for D3 visualizations [to pick two entirely random examples].
  • "Two-way data-binding" is avoided. While it certainly makes for a nifty demo, and works for the most basic CRUD, it doesn't tend to be terribly useful in your real-world app. Sometimes you want to update on every keypress, sometimes on blur, sometimes when the panel is closed, and sometimes when the "save" button is clicked. In almost all cases, simply serializing the form to JSON is faster and easier. All that aside, if your heart is set, go for it.
  • There's no built-in performance penalty for choosing to structure your code with Backbone. And if you do want to optimize further, thin models and templates with flexible granularity make it easy to squeeze every last drop of potential performance out of, say, IE8.

It's common for folks just getting started to treat the examples listed on this page as some sort of gospel truth. In fact, Backbone.js is intended to be fairly agnostic about many common patterns in client-side code. For example...

References between Models and Views can be handled several ways. Some people like to have direct pointers, where views correspond 1:1 with models [model.view and view.model]. Others prefer to have intermediate "controller" objects that orchestrate the creation and organization of views into a hierarchy. Others still prefer the evented approach, and always fire events instead of calling methods directly. All of these styles work well.

Batch operations on Models are common, but often best handled differently depending on your server-side setup. Some folks don't mind making individual Ajax requests. Others create explicit resources for RESTful batch operations: /notes/batch/destroy?ids=1,2,3,4. Others tunnel REST over JSON, with the creation of "changeset" requests:

proxy.on["all", function[eventName] { object.trigger[eventName]; }];

8

Feel free to define your own events. is designed so that you can mix it in to any JavaScript object or prototype. Since you can use any string as an event, it's often handy to bind and trigger your own custom events: model.on["selected:true"] or model.on["editing"]

Render the UI as you see fit. Backbone is agnostic as to whether you use , Mustache.js, direct DOM manipulation, server-side rendered snippets of HTML, or jQuery UI in your render function. Sometimes you'll create a view for each model ... sometimes you'll have a view that renders thousands of models at once, in a tight loop. Both can be appropriate in the same app, depending on the quantity of data involved, and the complexity of the UI.

It's common to nest collections inside of models with Backbone. For example, consider a Mailbox model that contains many Message models. One nice pattern for handling this is have a this.messages collection for each mailbox, enabling the lazy-loading of messages, when the mailbox is first opened ... perhaps with MessageList views listening for "add" and "remove" events.

proxy.on["all", function[eventName] { object.trigger[eventName]; }];

9

If you're looking for something more opinionated, there are a number of Backbone plugins that add sophisticated associations among models, available on the wiki.

Backbone doesn't include direct support for nested models and collections or "has many" associations because there are a number of good patterns for modeling structured data on the client side, and Backbone should provide the foundation for implementing any of them. You may want to…

  • Mirror an SQL database's structure, or the structure of a NoSQL database.
  • Use models with arrays of "foreign key" ids, and join to top level collections [a-la tables].
  • For associations that are numerous, use a range of ids instead of an explicit list.
  • Avoid ids, and use direct references, creating a partial object graph representing your data set.
  • Lazily load joined models from the server, or lazily deserialize nested models from JSON documents.

When your app first loads, it's common to have a set of initial models that you know you're going to need, in order to render the page. Instead of firing an extra AJAX request to them, a nicer pattern is to have their data already bootstrapped into the page. You can then use to populate your collections with the initial data. At DocumentCloud, in the ERB template for the workspace, we do something along these lines:

book.on[{ "change:author": authorPane.update, "change:title change:subtitle": titleView.update, "destroy": bookView.remove }];

0

You have to escape

Chủ Đề