Backbone.js là gì
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 long list of real-world projects 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")
Development Version (1.4.1) | 72kb, Full source, tons of comments |
Production Version (1.4.1) | 7.9kb, Packed and gzipped (Source Map) |
Edge Version (master) | Unreleased, use at your own risk |
Backbone"s only hard dependency is Underscore.js ( >= 1.8.3). For RESTful persistence and DOM manipulation with Backbone.View, 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 Models, 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 Views 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 list of Backbone-based projects.
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.
Bạn đang xem: Backbone.js là gì
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

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 Underscore template, 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)
onobject.on(event, callback,
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).
offobject.off(
// 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.
triggerobject.trigger(event, <*args>) Trigger callbacks for the given event, or space-delimited list of events. Subsequent arguments to trigger will be passed along to the event callbacks.
onceobject.once(event, callback,
listenToobject.listenTo(other, event, callback) 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.
view.listenTo(model, "change", view.render); stopListeningobject.stopListening(
view.stopListening();view.stopListening(model); listenToOnceobject.listenToOnce(other, event, callback) Just like listenTo, but causes the bound callback to fire only once before being removed.
Catalog of Events 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. "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: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.
var Sidebar = Backbone.Model.extend({ promptColor: function() { var cssColor = prompt("Please enter a CSS color:"); this.set({color: cssColor}); }});window.sidebar = new Sidebar;sidebar.on("change:color", function(model, color) { $("#sidebar").css({background: color});});sidebar.set({color: "white"});sidebar.promptColor(); extendBackbone.Model.extend(properties,
extend correctly sets up the prototype chain, so subclasses created with extend can be further extended and subclassed as far as you like.
var Note = Backbone.Model.extend({ initialize: function() { ... }, author: function() { ... }, coordinates: function() { ... }, allowedToEdit: function(account) { return true; }});var PrivateNote = Note.extend({ allowedToEdit: function(account) { return account.owns(this); }}); 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:
var Note = Backbone.Model.extend({ set: function(attributes, options) { Backbone.Model.prototype.set.apply(this, arguments); ... }}); preinitializenew Model(
class Country extends Backbone.Model { preinitialize({countryCode}) { this.name = COUNTRY_NAMES
new Book({ title: "One Thousand and One Nights", author: "Scheherazade"}); 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.
var Library = Backbone.Model.extend({ constructor: function() { this.books = new Books(); Backbone.Model.apply(this, arguments); }, parse: function(data, options) { this.books.reset(data.books); return data.library; }}); If you pass a {collection: ...} as the options, the model gains a collection property that will be used to indicate which collection the model belongs to, and is used to help compute the model"s url. The model.collection property is normally created automatically when you first add a model to a collection. Note that the reverse is not true, as passing this option to the constructor will not automatically add the model to the collection. Useful, sometimes.
If {parse: true} is passed as an option, the attributes will first be converted by parse before being set on the model.
getmodel.get(attribute) Get the current value of an attribute from the model. For example: note.get("title")
setmodel.set(attributes,
note.set({title: "March 20", content: "In his eyes she eclipses..."});book.set("title", "A Scandal in Bohemia"); escapemodel.escape(attribute) Similar to get, but returns the HTML-escaped version of a model"s attribute. If you"re interpolating data from the model into HTML, using escape to retrieve attributes will prevent XSS attacks.
var hacker = new Backbone.Model({ name: ""});alert(hacker.escape("name")); hasmodel.has(attribute) Returns true if the attribute is set to a non-null or non-undefined value.
if (note.has("title")) { ...} unsetmodel.unset(attribute,
clearmodel.clear(
idmodel.id 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. model.id should not be manipulated directly, it should be modified only via model.set("id", …). Models can be retrieved by id from collections, and the id is used to generate model URLs by default.
idAttributemodel.idAttribute 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.var Meal = Backbone.Model.extend({ idAttribute: "_id"});var cake = new Meal({ _id: 1, name: "Cake" });alert("Cake id: " + cake.id);
cidmodel.cid 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.
attributesmodel.attributes 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 set 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 Events accepts space separated lists of events, attribute names should not include spaces.
changedmodel.changed The changed property is the internal hash containing all the attributes that have changed since its last set. Please do not update changed directly since its state is internally maintained by set. A copy of changed can be acquired from changedAttributes.
defaultsmodel.defaults or model.defaults() 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.
var Meal = Backbone.Model.extend({ defaults: { "appetizer": "caesar salad", "entree": "ravioli", "dessert": "cheesecake" }});alert("Dessert will be " + (new Meal).get("dessert")); 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.
toJSONmodel.toJSON(
var artist = new Backbone.Model({ firstName: "Wassily", lastName: "Kandinsky"});artist.set({birthday: "December 16, 1866"});alert(JSON.stringify(artist)); syncmodel.sync(method, model,
fetchmodel.fetch(
// Poll every 10 seconds to keep the channel model up-to-date.setInterval(function() { channel.fetch();}, 10000); savemodel.save(
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.
Backbone.sync = function(method, model) { alert(method + ": " + JSON.stringify(model)); model.set("id", 1);};var book = new Backbone.Model({ title: "The Rough Riders", author: "Theodore Roosevelt"});book.save();book.save({author: "Teddy"}); 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.
book.save("author", "F.D.R.", {error: function(){ ... }}); destroymodel.destroy(
book.destroy({success: function(model, response) { ...}}); Underscore Methods (9) 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…
user.pick("first_name", "last_name", "email");chapters.keys().join(", "); validatemodel.validate(attributes, options) 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.
var Chapter = Backbone.Model.extend({ validate: function(attrs, options) { if (attrs.end "invalid" events are useful for providing coarse-grained error messages at the model or collection level.
validationErrormodel.validationError The value returned by validate during the last failed validation.
isValidmodel.isValid(options) Run validate 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.
var Chapter = Backbone.Model.extend({ validate: function(attrs, options) { if (attrs.end urlmodel.url() 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: "
Delegates to Collection#url to generate the URL, so make sure that you have it defined, or a urlRoot property, if all models of this class share a common root URL. A model with an id of 101, stored in a Backbone.Collection with a url of "/documents/7/notes", would have this URL: "/documents/7/notes/101"
urlRootmodel.urlRoot or model.urlRoot() Specify a urlRoot if you"re using a model outside of a collection, to enable the default url function to generate URLs based on the model id. "
var Book = Backbone.Model.extend({urlRoot : "/books"});var solaris = new Book({id: "1083-lem-solaris"});alert(solaris.url()); parsemodel.parse(response, options) parse is called whenever a model"s data is returned by the server, in fetch, and save. The function is passed the raw response object, and should return the attributes hash to be set on the model. The default implementation is a no-op, simply passing through the JSON response. Override this if you need to work with a preexisting API, or better namespace your responses.
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:
ActiveRecord::Base.include_root_in_json = false clonemodel.clone() Returns a new instance of the model with identical attributes.
Xem thêm: Tải Miễn Phí Nhạc Chuông Tin Nhắn Điện Thoại Hay Nhất 2021 Cho Điện Thoại
Xem thêm: Top 5 Nước Hoa Versace Nữ Mùi Nào Thơm Nhất ? Review 10 Sản Phẩm
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(
Note that this method, and the following change-related ones, are only useful during the course of a "change" event.
book.on("change", function() { if (book.hasChanged("title")) { ... }}); changedAttributesmodel.changedAttributes(
previousmodel.previous(attribute) During a "change" event, this method can be used to get the previous value of a changed attribute.
var bill = new Backbone.Model({ name: "Bill Smith"});bill.on("change:name", function(model, name) { alert("Changed name from " + bill.previous("name") + " to " + name);});bill.set({name : "Bill Jones"}); 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.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 Underscore.js methods.
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", ...)
extendBackbone.Collection.extend(properties,
modelcollection.model(
var Library = Backbone.Collection.extend({ model: Book}); A collection can also contain polymorphic models by overriding this property with a constructor that returns a model.
var Library = Backbone.Collection.extend({ model: function(attrs, options) { if (condition) { return new PublicDocument(attrs, options); } else { return new PrivateDocument(attrs, options); } }}); modelIdcollection.modelId(attrs, idAttribute) 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 idAttribute values into a single collection.
By default returns the value of the given idAttribute within the attrs, or failing that, id. If your collection uses a model factory and the id ranges of those models might collide, you must override this method.
var Library = Backbone.Collection.extend({ modelId: function(attrs) { return attrs.type + attrs.id; }});var library = new Library(< {type: "dvd", id: 1}, {type: "vhs", id: 1}>);var dvdId = library.get("dvd1").id;var vhsId = library.get("vhs1").id;alert("dvd: " + dvdId + ", vhs: " + vhsId); preinitializenew Backbone.Collection(
class Library extends Backbone.Collection { preinitialize() { this.on("add", function() { console.log("Add model event got fired!"); }); }} constructor / initializenew Backbone.Collection(
var tabs = new TabSet(
toJSONcollection.toJSON(
var collection = new Backbone.Collection(< {name: "Tim", age: 5}, {name: "Ida", age: 26}, {name: "Rob", age: 55}>);alert(JSON.stringify(collection)); synccollection.sync(method, collection,
Underscore Methods (46) 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.
books.each(function(book) { book.publish();});var titles = books.map("title");var publishedBooks = books.filter({published: true});var alphabetical = books.sortBy(function(book) { return book.author.get("name").toLowerCase();});var randomThree = books.sample(3); addcollection.add(models,
var ships = new Backbone.Collection;ships.on("add", function(ship) { alert("Ahoy " + ship.get("name") + "!");});ships.add(< {name: "Flying Dutchman"}, {name: "Black Pearl"}>); Note that adding the same model (a model with the same id) to a collection more than once is a no-op.
removecollection.remove(models,
resetcollection.reset(
Here"s an example using reset to bootstrap a collection during initial page load, in a Rails application:
Calling collection.reset() without passing any models as arguments will empty the entire collection.
setcollection.set(models,
var vanHalen = new Backbone.Collection(
var book = library.get(110); atcollection.at(index) 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.
pushcollection.push(model,
popcollection.pop(
unshiftcollection.unshift(model,
shiftcollection.shift(
slicecollection.slice(begin, end) Return a shallow copy of this collection"s models, using the same options as native Array#slice.
lengthcollection.length Like an array, a Collection maintains a length property, counting the number of models it contains.
comparatorcollection.comparator 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 sortBy (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 Chapter = Backbone.Model;var chapters = new Backbone.Collection;chapters.comparator = "page";chapters.add(new Chapter({page: 9, title: "The End"}));chapters.add(new Chapter({page: 5, title: "The Middle"}));chapters.add(new Chapter({page: 1, title: "The Beginning"}));alert(chapters.pluck("title")); 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.
sortcollection.sort(
pluckcollection.pluck(attribute) Pluck an attribute from each model in the collection. Equivalent to calling map and returning a single attribute from the iterator.
var stooges = new Backbone.Collection(< {name: "Curly"}, {name: "Larry"}, {name: "Moe"}>);var names = stooges.pluck("name");alert(JSON.stringify(names)); wherecollection.where(attributes) Return an array of all the models in a collection that match the passed attributes. Useful for simple cases of filter.
var friends = new Backbone.Collection(< {name: "Athos", job: "Musketeer"}, {name: "Porthos", job: "Musketeer"}, {name: "Aramis", job: "Musketeer"}, {name: "d"Artagnan", job: "Guard"},>);var musketeers = friends.where({job: "Musketeer"});alert(musketeers.length); findWherecollection.findWhere(attributes) Just like where, but directly returns only the first model in the collection that matches the passed attributes. If no model matches returns undefined.
urlcollection.url or collection.url() 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 Notes = Backbone.Collection.extend({ url: "/notes"});// Or, something more sophisticated:var Notes = Backbone.Collection.extend({ url: function() { return this.document.url() + "/notes"; }}); parsecollection.parse(response, options) parse is called by Backbone whenever a collection"s models are returned by the server, in fetch. The function is passed the raw response object, and should return the array of model attributes to be added 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 Tweets = Backbone.Collection.extend({ // The Twitter Search API returns tweets under "results". parse: function(response) { return response.results; }}); clonecollection.clone() Returns a new instance of the collection with an identical list of models.
fetchcollection.fetch(
Backbone.sync = function(method, model) { alert(method + ": " + model.url);};var accounts = new Backbone.Collection;accounts.url = "/accounts";accounts.fetch(); The behavior of fetch can be customized by using the available set 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 bootstrapped 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.
createcollection.create(attributes,
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 Library = Backbone.Collection.extend({ model: Book});var nypl = new Library;var othello = nypl.create({ title: "Othello", author: "William Shakespeare"}); mixinBackbone.Collection.mixin(properties) mixin 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 Underscore Methods).
Backbone.Collection.mixin({ sum: function(models, iteratee) { return _.reduce(models, function(s, m) { return s + iteratee(m); }, 0); }});var cart = new Backbone.Collection(< {price: 16, name: "monopoly"}, {price: 5, name: "deck of cards"}, {price: 20, name: "chess"}>);var cost = cart.sum("price");
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.
extendBackbone.Router.extend(properties,
var Workspace = Backbone.Router.extend({ routes: { "help": "help", // #help "search/:query": "search", // #search/kiwis "search/:query/p:page": "search" // #search/kiwis/p7 }, help: function() { ... }, search: function(query, page) { ... }}); routesrouter.routes The routes hash maps URLs with parameters to functions on your router (or just direct function definitions, if you prefer), similar to the View"s events hash. 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 event, 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.
routes: { "help/:page": "help", "download/*path": "download", "folder/:name": "openFolder", "folder/:name-:mode": "openFolder"}router.on("route:help", function(page) { ...}); preinitializenew Backbone.Router(
class Router extends Backbone.Router { preinitialize() { // Override execute method this.execute = function(callback, args, name) { if (!loggedIn) { goToLogin(); return false; } args.push(parseQueryString(args.pop())); if (callback) callback.apply(this, args); } }} constructor / initializenew Router(
routerouter.route(route, name,
initialize: function(options) { // Matches #page/10, passing "10" this.route("page/:number", "page", function(number){ ... }); // Matches /117-a/b/c/open, passing "117-a/b/c" to this.open this.route(/^(.*?)\/open$/, "open");},open: function(id) { ... } navigaterouter.navigate(fragment,
openPage: function(pageNumber) { this.document.pages.at(pageNumber).open(); this.navigate("page/" + pageNumber);}# Or ...app.navigate("help/troubleshooting", {trigger: true});# Or ...app.navigate("help/troubleshooting", {trigger: true, replace: true}); executerouter.execute(callback, args, name) 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:
var Router = Backbone.Router.extend({ execute: function(callback, args, name) { if (!loggedIn) { goToLogin(); return false; } args.push(parseQueryString(args.pop())); if (callback) callback.apply(this, args); }});
Backbone.history
History serves as a global router (per frame) to handle hashchange events or pushState, match the appropriate route, and trigger callbacks. 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.
startBackbone.history.start(
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/"})
When called, if a route succeeds with a match for the current URL, Backbone.history.start() returns true. If no defined route matches the current URL, it returns false.
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.
$(function(){ new WorkspaceRouter(); new HelpPaneRouter(); Backbone.history.start({pushState: true});});
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 jqXHR. 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,
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 (Collection#fetch), 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 update → PUT /collection/id patch → PATCH /collection/id delete → DELETE /collection/idAs an example, a Rails 4 handler responding to an "update" call from Backbone might look like this:
def update account = Account.find params<:id> permitted = params.require(:account).permit(:name, :otherparam) account.update_attributes permitted render :json => accountend 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
ajaxBackbone.ajax = function(request) { ... }; 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.
emulateHTTPBackbone.emulateHTTP = true 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.
Backbone.emulateHTTP = true;model.save(); // POST to "/collection/id", with "_method=PUT" + header. emulateJSONBackbone.emulateJSON = true 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.
extendBackbone.View.extend(properties,
var DocumentRow = Backbone.View.extend({ tagName: "li", className: "document-row", events: { "click .icon": "open", "click .button.edit": "openEditDialog", "click .button.delete": "destroy" }, initialize: function() { this.listenTo(this.model, "change", this.render); }, render: function() { ... }}); 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.
preinitializenew View(
class Document extends Backbone.View { preinitialize({autoRender}) { this.autoRender = autoRender; } initialize() { if (this.autoRender) { this.listenTo(this.model, "change", this.render); } }} constructor / initializenew View(
var doc = documents.first();new DocumentRow({ model: doc, id: "document-row-" + doc.id}); elview.el 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 attributes 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.
var ItemView = Backbone.View.extend({ tagName: "li"});var BodyView = Backbone.View.extend({ el: "body"});var item = new ItemView();var body = new BodyView();alert(item.el + " " + body.el); $elview.$el A cached jQuery object for the view"s element. A handy reference instead of re-wrapping the DOM element all the time.
view.$el.show();listView.$el.append(itemView.el); setElementview.setElement(element) If you"d like to apply a Backbone view to a different DOM element, use setElement, which will