PageRenderTime 76ms CodeModel.GetById 35ms RepoModel.GetById 0ms app.codeStats 1ms

/backbone.js

https://github.com/harshniketseta/backbone
JavaScript | 1553 lines | 930 code | 224 blank | 399 comment | 318 complexity | dca9e59e70ec66e5d29ff183d6668f38 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. // Backbone.js 0.9.9
  2. // (c) 2010-2012 Jeremy Ashkenas, DocumentCloud Inc.
  3. // Backbone may be freely distributed under the MIT license.
  4. // For all details and documentation:
  5. // http://backbonejs.org
  6. (function(){
  7. // Initial Setup
  8. // -------------
  9. // Save a reference to the global object (`window` in the browser, `exports`
  10. // on the server).
  11. var root = this;
  12. // Save the previous value of the `Backbone` variable, so that it can be
  13. // restored later on, if `noConflict` is used.
  14. var previousBackbone = root.Backbone;
  15. // Create a local reference to array methods.
  16. var array = [];
  17. var push = array.push;
  18. var slice = array.slice;
  19. var splice = array.splice;
  20. // The top-level namespace. All public Backbone classes and modules will
  21. // be attached to this. Exported for both CommonJS and the browser.
  22. var Backbone;
  23. if (typeof exports !== 'undefined') {
  24. Backbone = exports;
  25. } else {
  26. Backbone = root.Backbone = {};
  27. }
  28. // Current version of the library. Keep in sync with `package.json`.
  29. Backbone.VERSION = '0.9.9';
  30. // Require Underscore, if we're on the server, and it's not already present.
  31. var _ = root._;
  32. if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
  33. // For Backbone's purposes, jQuery, Zepto, or Ender owns the `$` variable.
  34. Backbone.$ = root.jQuery || root.Zepto || root.ender;
  35. // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
  36. // to its previous owner. Returns a reference to this Backbone object.
  37. Backbone.noConflict = function() {
  38. root.Backbone = previousBackbone;
  39. return this;
  40. };
  41. // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
  42. // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and
  43. // set a `X-Http-Method-Override` header.
  44. Backbone.emulateHTTP = false;
  45. // Turn on `emulateJSON` to support legacy servers that can't deal with direct
  46. // `application/json` requests ... will encode the body as
  47. // `application/x-www-form-urlencoded` instead and will send the model in a
  48. // form param named `model`.
  49. Backbone.emulateJSON = false;
  50. // Backbone.Events
  51. // ---------------
  52. // Regular expression used to split event strings.
  53. var eventSplitter = /\s+/;
  54. // Implement fancy features of the Events API such as multiple event
  55. // names `"change blur"` and jQuery-style event maps `{change: action}`
  56. // in terms of the existing API.
  57. var eventsApi = function(obj, action, name, rest) {
  58. if (!name) return true;
  59. if (typeof name === 'object') {
  60. for (var key in name) {
  61. obj[action].apply(obj, [key, name[key]].concat(rest));
  62. }
  63. } else if (eventSplitter.test(name)) {
  64. var names = name.split(eventSplitter);
  65. for (var i = 0, l = names.length; i < l; i++) {
  66. obj[action].apply(obj, [names[i]].concat(rest));
  67. }
  68. } else {
  69. return true;
  70. }
  71. };
  72. // Optimized internal dispatch function for triggering events. Tries to
  73. // keep the usual cases speedy (most Backbone events have 3 arguments).
  74. var triggerEvents = function(obj, events, args) {
  75. var ev, i = -1, l = events.length;
  76. switch (args.length) {
  77. case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx);
  78. return;
  79. case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, args[0]);
  80. return;
  81. case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, args[0], args[1]);
  82. return;
  83. case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, args[0], args[1], args[2]);
  84. return;
  85. default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
  86. }
  87. };
  88. // A module that can be mixed in to *any object* in order to provide it with
  89. // custom events. You may bind with `on` or remove with `off` callback
  90. // functions to an event; `trigger`-ing an event fires all callbacks in
  91. // succession.
  92. //
  93. // var object = {};
  94. // _.extend(object, Backbone.Events);
  95. // object.on('expand', function(){ alert('expanded'); });
  96. // object.trigger('expand');
  97. //
  98. var Events = Backbone.Events = {
  99. // Bind one or more space separated events, or an events map,
  100. // to a `callback` function. Passing `"all"` will bind the callback to
  101. // all events fired.
  102. on: function(name, callback, context) {
  103. if (!(eventsApi(this, 'on', name, [callback, context]) && callback)) return this;
  104. this._events || (this._events = {});
  105. var list = this._events[name] || (this._events[name] = []);
  106. list.push({callback: callback, context: context, ctx: context || this});
  107. return this;
  108. },
  109. // Bind events to only be triggered a single time. After the first time
  110. // the callback is invoked, it will be removed.
  111. once: function(name, callback, context) {
  112. if (!(eventsApi(this, 'once', name, [callback, context]) && callback)) return this;
  113. var self = this;
  114. var once = _.once(function() {
  115. self.off(name, once);
  116. callback.apply(this, arguments);
  117. });
  118. once._callback = callback;
  119. this.on(name, once, context);
  120. return this;
  121. },
  122. // Remove one or many callbacks. If `context` is null, removes all
  123. // callbacks with that function. If `callback` is null, removes all
  124. // callbacks for the event. If `events` is null, removes all bound
  125. // callbacks for all events.
  126. off: function(name, callback, context) {
  127. var list, ev, events, names, i, l, j, k;
  128. if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
  129. if (!name && !callback && !context) {
  130. this._events = {};
  131. return this;
  132. }
  133. names = name ? [name] : _.keys(this._events);
  134. for (i = 0, l = names.length; i < l; i++) {
  135. name = names[i];
  136. if (list = this._events[name]) {
  137. events = [];
  138. if (callback || context) {
  139. for (j = 0, k = list.length; j < k; j++) {
  140. ev = list[j];
  141. if ((callback && callback !== (ev.callback._callback || ev.callback)) ||
  142. (context && context !== ev.context)) {
  143. events.push(ev);
  144. }
  145. }
  146. }
  147. this._events[name] = events;
  148. }
  149. }
  150. return this;
  151. },
  152. // Trigger one or many events, firing all bound callbacks. Callbacks are
  153. // passed the same arguments as `trigger` is, apart from the event name
  154. // (unless you're listening on `"all"`, which will cause your callback to
  155. // receive the true name of the event as the first argument).
  156. trigger: function(name) {
  157. if (!this._events) return this;
  158. var args = slice.call(arguments, 1);
  159. if (!eventsApi(this, 'trigger', name, args)) return this;
  160. var events = this._events[name];
  161. var allEvents = this._events.all;
  162. if (events) triggerEvents(this, events, args);
  163. if (allEvents) triggerEvents(this, allEvents, arguments);
  164. return this;
  165. },
  166. // An inversion-of-control version of `on`. Tell *this* object to listen to
  167. // an event in another object ... keeping track of what it's listening to.
  168. listenTo: function(object, events, callback, context) {
  169. context = context || this;
  170. var listeners = this._listeners || (this._listeners = {});
  171. var id = object._listenerId || (object._listenerId = _.uniqueId('l'));
  172. listeners[id] = object;
  173. object.on(events, callback || context, context);
  174. return this;
  175. },
  176. // Tell this object to stop listening to either specific events ... or
  177. // to every object it's currently listening to.
  178. stopListening: function(object, events, callback, context) {
  179. context = context || this;
  180. var listeners = this._listeners;
  181. if (!listeners) return;
  182. if (object) {
  183. object.off(events, callback, context);
  184. if (!events && !callback) delete listeners[object._listenerId];
  185. } else {
  186. for (var id in listeners) {
  187. listeners[id].off(null, null, context);
  188. }
  189. this._listeners = {};
  190. }
  191. return this;
  192. }
  193. };
  194. // Aliases for backwards compatibility.
  195. Events.bind = Events.on;
  196. Events.unbind = Events.off;
  197. // Allow the `Backbone` object to serve as a global event bus, for folks who
  198. // want global "pubsub" in a convenient place.
  199. _.extend(Backbone, Events);
  200. // Backbone.Model
  201. // --------------
  202. // Create a new model, with defined attributes. A client id (`cid`)
  203. // is automatically generated and assigned for you.
  204. var Model = Backbone.Model = function(attributes, options) {
  205. var defaults;
  206. var attrs = attributes || {};
  207. this.cid = _.uniqueId('c');
  208. this.changed = {};
  209. this.attributes = {};
  210. this._changes = [];
  211. if (options && options.collection) this.collection = options.collection;
  212. if (options && options.parse) attrs = this.parse(attrs, options);
  213. if (defaults = _.result(this, 'defaults')) {
  214. attrs = _.defaults({}, attrs, defaults);
  215. }
  216. this.set(attrs, _.extend({silent: true}, options));
  217. this._currentAttributes = _.clone(this.attributes);
  218. this._previousAttributes = _.clone(this.attributes);
  219. this.initialize.apply(this, arguments);
  220. };
  221. // Attach all inheritable methods to the Model prototype.
  222. _.extend(Model.prototype, Events, {
  223. // A hash of attributes whose current and previous value differ.
  224. changed: null,
  225. // The default name for the JSON `id` attribute is `"id"`. MongoDB and
  226. // CouchDB users may want to set this to `"_id"`.
  227. idAttribute: 'id',
  228. // Initialize is an empty function by default. Override it with your own
  229. // initialization logic.
  230. initialize: function(){},
  231. // Return a copy of the model's `attributes` object.
  232. toJSON: function(options) {
  233. return _.clone(this.attributes);
  234. },
  235. // Proxy `Backbone.sync` by default.
  236. sync: function() {
  237. return Backbone.sync.apply(this, arguments);
  238. },
  239. // Get the value of an attribute.
  240. get: function(attr) {
  241. return this.attributes[attr];
  242. },
  243. // Get the HTML-escaped value of an attribute.
  244. escape: function(attr) {
  245. return _.escape(this.get(attr));
  246. },
  247. // Returns `true` if the attribute contains a value that is not null
  248. // or undefined.
  249. has: function(attr) {
  250. return this.get(attr) != null;
  251. },
  252. // Set a hash of model attributes on the object, firing `"change"` unless
  253. // you choose to silence it.
  254. set: function(key, val, options) {
  255. var attr, attrs;
  256. if (key == null) return this;
  257. // Handle both `"key", value` and `{key: value}` -style arguments.
  258. if (typeof key === 'object') {
  259. attrs = key;
  260. options = val;
  261. } else {
  262. (attrs = {})[key] = val;
  263. }
  264. // Extract attributes and options.
  265. var silent = options && options.silent;
  266. var unset = options && options.unset;
  267. // Run validation.
  268. if (!this._validate(attrs, options)) return false;
  269. // Check for changes of `id`.
  270. if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
  271. var now = this.attributes;
  272. // For each `set` attribute...
  273. for (attr in attrs) {
  274. val = attrs[attr];
  275. // Update or delete the current value, and track the change.
  276. unset ? delete now[attr] : now[attr] = val;
  277. this._changes.push(attr, val);
  278. }
  279. // Signal that the model's state has potentially changed, and we need
  280. // to recompute the actual changes.
  281. this._hasComputed = false;
  282. // Fire the `"change"` events.
  283. if (!silent) this.change(options);
  284. return this;
  285. },
  286. // Remove an attribute from the model, firing `"change"` unless you choose
  287. // to silence it. `unset` is a noop if the attribute doesn't exist.
  288. unset: function(attr, options) {
  289. return this.set(attr, void 0, _.extend({}, options, {unset: true}));
  290. },
  291. // Clear all attributes on the model, firing `"change"` unless you choose
  292. // to silence it.
  293. clear: function(options) {
  294. var attrs = {};
  295. for (var key in this.attributes) attrs[key] = void 0;
  296. return this.set(attrs, _.extend({}, options, {unset: true}));
  297. },
  298. // Fetch the model from the server. If the server's representation of the
  299. // model differs from its current attributes, they will be overriden,
  300. // triggering a `"change"` event.
  301. fetch: function(options) {
  302. options = options ? _.clone(options) : {};
  303. if (options.parse === void 0) options.parse = true;
  304. var model = this;
  305. var success = options.success;
  306. options.success = function(resp, status, xhr) {
  307. if (!model.set(model.parse(resp, options), options)) return false;
  308. if (success) success(model, resp, options);
  309. };
  310. return this.sync('read', this, options);
  311. },
  312. // Set a hash of model attributes, and sync the model to the server.
  313. // If the server returns an attributes hash that differs, the model's
  314. // state will be `set` again.
  315. save: function(key, val, options) {
  316. var attrs, current, done;
  317. // Handle both `"key", value` and `{key: value}` -style arguments.
  318. if (key === void 0 || typeof key === 'object') {
  319. attrs = key;
  320. options = val;
  321. } else if (key != null) {
  322. (attrs = {})[key] = val;
  323. }
  324. options = _.extend({validate: true}, options);
  325. // If we're "wait"-ing to set changed attributes, validate early.
  326. if (options.wait) {
  327. if (attrs && !this._validate(attrs, options)) return false;
  328. current = _.clone(this.attributes);
  329. }
  330. // Regular saves `set` attributes before persisting to the server.
  331. var silentOptions = _.extend({}, options, {silent: true});
  332. if (attrs && !this.set(attrs, options.wait ? silentOptions : options)) {
  333. return false;
  334. }
  335. // Do not persist invalid models.
  336. if (!attrs && !this._validate(null, options)) return false;
  337. // After a successful server-side save, the client is (optionally)
  338. // updated with the server-side state.
  339. var model = this;
  340. var success = options.success;
  341. options.success = function(resp, status, xhr) {
  342. done = true;
  343. var serverAttrs = model.parse(resp, options);
  344. if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
  345. if (!model.set(serverAttrs, options)) return false;
  346. if (success) success(model, resp, options);
  347. };
  348. // Finish configuring and sending the Ajax request.
  349. var method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
  350. if (method == 'patch') options.attrs = attrs;
  351. var xhr = this.sync(method, this, options);
  352. // When using `wait`, reset attributes to original values unless
  353. // `success` has been called already.
  354. if (!done && options.wait) {
  355. this.clear(silentOptions);
  356. this.set(current, silentOptions);
  357. }
  358. return xhr;
  359. },
  360. // Destroy this model on the server if it was already persisted.
  361. // Optimistically removes the model from its collection, if it has one.
  362. // If `wait: true` is passed, waits for the server to respond before removal.
  363. destroy: function(options) {
  364. options = options ? _.clone(options) : {};
  365. var model = this;
  366. var success = options.success;
  367. var destroy = function() {
  368. model.trigger('destroy', model, model.collection, options);
  369. };
  370. options.success = function(resp) {
  371. if (options.wait || model.isNew()) destroy();
  372. if (success) success(model, resp, options);
  373. };
  374. if (this.isNew()) {
  375. options.success();
  376. return false;
  377. }
  378. var xhr = this.sync('delete', this, options);
  379. if (!options.wait) destroy();
  380. return xhr;
  381. },
  382. // Default URL for the model's representation on the server -- if you're
  383. // using Backbone's restful methods, override this to change the endpoint
  384. // that will be called.
  385. url: function() {
  386. var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError();
  387. if (this.isNew()) return base;
  388. return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id);
  389. },
  390. // **parse** converts a response into the hash of attributes to be `set` on
  391. // the model. The default implementation is just to pass the response along.
  392. parse: function(resp, options) {
  393. return resp;
  394. },
  395. // Create a new model with identical attributes to this one.
  396. clone: function() {
  397. return new this.constructor(this.attributes);
  398. },
  399. // A model is new if it has never been saved to the server, and lacks an id.
  400. isNew: function() {
  401. return this.id == null;
  402. },
  403. // Call this method to manually fire a `"change"` event for this model and
  404. // a `"change:attribute"` event for each changed attribute.
  405. // Calling this will cause all objects observing the model to update.
  406. change: function(options) {
  407. options || (options = {});
  408. var changing = this._changing;
  409. this._changing = true;
  410. // Generate the changes to be triggered on the model.
  411. var triggers = this._computeChanges(true);
  412. var pending = this._pending = !!triggers.length;
  413. for (var i = triggers.length - 2; i >= 0; i -= 2) {
  414. this.trigger('change:' + triggers[i], this, triggers[i + 1], options);
  415. }
  416. if (changing) return this;
  417. // Ensure the original `change` event is fired regardless of interim changes
  418. if (pending) this._pending = true;
  419. // Trigger a `change` while there have been changes.
  420. while (this._pending) {
  421. this._pending = false;
  422. this.trigger('change', this, options);
  423. this._previousAttributes = _.clone(this.attributes);
  424. }
  425. this._changing = false;
  426. return this;
  427. },
  428. // Determine if the model has changed since the last `"change"` event.
  429. // If you specify an attribute name, determine if that attribute has changed.
  430. hasChanged: function(attr) {
  431. if (!this._hasComputed) this._computeChanges();
  432. if (attr == null) return !_.isEmpty(this.changed);
  433. return _.has(this.changed, attr);
  434. },
  435. // Return an object containing all the attributes that have changed, or
  436. // false if there are no changed attributes. Useful for determining what
  437. // parts of a view need to be updated and/or what attributes need to be
  438. // persisted to the server. Unset attributes will be set to undefined.
  439. // You can also pass an attributes object to diff against the model,
  440. // determining if there *would be* a change.
  441. changedAttributes: function(diff) {
  442. if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
  443. var val, changed = false, old = this._previousAttributes;
  444. for (var attr in diff) {
  445. if (_.isEqual(old[attr], (val = diff[attr]))) continue;
  446. (changed || (changed = {}))[attr] = val;
  447. }
  448. return changed;
  449. },
  450. // Looking at the built up list of `set` attribute changes, compute how
  451. // many of the attributes have actually changed. If `loud`, return a
  452. // boiled-down list of only the real changes.
  453. _computeChanges: function(loud) {
  454. this.changed = {};
  455. var already = {};
  456. var triggers = [];
  457. var current = this._currentAttributes;
  458. var changes = this._changes;
  459. // Loop through the current queue of potential model changes.
  460. for (var i = changes.length - 2; i >= 0; i -= 2) {
  461. var key = changes[i], val = changes[i + 1];
  462. if (already[key]) continue;
  463. already[key] = true;
  464. // Check if the attribute has been modified since the last change,
  465. // and update `this.changed` accordingly. If we're inside of a `change`
  466. // call, also add a trigger to the list.
  467. if (!_.isEqual(current[key], val)) {
  468. this.changed[key] = val;
  469. if (!loud) continue;
  470. triggers.push(key, val);
  471. current[key] = val;
  472. }
  473. }
  474. if (loud) this._changes = [];
  475. // Signals `this.changed` is current to prevent duplicate calls from `this.hasChanged`.
  476. this._hasComputed = true;
  477. return triggers;
  478. },
  479. // Get the previous value of an attribute, recorded at the time the last
  480. // `"change"` event was fired.
  481. previous: function(attr) {
  482. if (attr == null || !this._previousAttributes) return null;
  483. return this._previousAttributes[attr];
  484. },
  485. // Get all of the attributes of the model at the time of the previous
  486. // `"change"` event.
  487. previousAttributes: function() {
  488. return _.clone(this._previousAttributes);
  489. },
  490. // Check if the model is currently in a valid state. It's only possible to
  491. // get into an *invalid* state if you're using silent changes.
  492. isValid: function(options) {
  493. return !this.validate || !this.validate(this.attributes, options);
  494. },
  495. // Run validation against the next complete set of model attributes,
  496. // returning `true` if all is well. Otherwise, fire a general
  497. // `"error"` event and call the error callback, if specified.
  498. _validate: function(attrs, options) {
  499. if (!options || !options.validate || !this.validate) return true;
  500. options || (options = {});
  501. attrs = _.extend({}, this.attributes, attrs);
  502. var error = this.validationError = this.validate(attrs, options) || null;
  503. if (!error) return true;
  504. this.trigger('invalid', this, error, options);
  505. return false;
  506. }
  507. });
  508. // Backbone.Collection
  509. // -------------------
  510. // Provides a standard collection class for our sets of models, ordered
  511. // or unordered. If a `comparator` is specified, the Collection will maintain
  512. // its models in sort order, as they're added and removed.
  513. var Collection = Backbone.Collection = function(models, options) {
  514. options || (options = {});
  515. if (options.model) this.model = options.model;
  516. if (options.comparator !== void 0) this.comparator = options.comparator;
  517. this._reset();
  518. this.initialize.apply(this, arguments);
  519. if (models) this.reset(models, _.extend({silent: true}, options));
  520. };
  521. // Define the Collection's inheritable methods.
  522. _.extend(Collection.prototype, Events, {
  523. // The default model for a collection is just a **Backbone.Model**.
  524. // This should be overridden in most cases.
  525. model: Model,
  526. // Initialize is an empty function by default. Override it with your own
  527. // initialization logic.
  528. initialize: function(){},
  529. // The JSON representation of a Collection is an array of the
  530. // models' attributes.
  531. toJSON: function(options) {
  532. return this.map(function(model){ return model.toJSON(options); });
  533. },
  534. // Proxy `Backbone.sync` by default.
  535. sync: function() {
  536. return Backbone.sync.apply(this, arguments);
  537. },
  538. // Add a model, or list of models to the set. Pass **silent** to avoid
  539. // firing the `add` event for every new model.
  540. add: function(models, options) {
  541. options || (options = {});
  542. var i, args, length, model, attrs, existing, needsSort;
  543. var at = options.at;
  544. var sort = options.sort == null ? true : options.sort;
  545. models = _.isArray(models) ? models.slice() : [models];
  546. // Turn bare objects into model references, and prevent invalid models
  547. // from being added.
  548. for (i = models.length - 1; i >= 0; i--) {
  549. attrs = models[i];
  550. if(!(model = this._prepareModel(attrs, options))) {
  551. this.trigger('invalid', this, attrs, options);
  552. models.splice(i, 1);
  553. continue;
  554. }
  555. models[i] = model;
  556. // If a duplicate is found, prevent it from being added and
  557. // optionally merge it into the existing model.
  558. if (existing = this.get(model)) {
  559. if (options.merge) {
  560. existing.set(attrs != model ? attrs : model.attributes, options);
  561. needsSort = sort;
  562. }
  563. models.splice(i, 1);
  564. continue;
  565. }
  566. // Listen to added models' events, and index models for lookup by
  567. // `id` and by `cid`.
  568. model.on('all', this._onModelEvent, this);
  569. this._byId[model.cid] = model;
  570. if (model.id != null) this._byId[model.id] = model;
  571. }
  572. // See if sorting is needed, update `length` and splice in new models.
  573. if (models.length) needsSort = sort;
  574. this.length += models.length;
  575. args = [at != null ? at : this.models.length, 0];
  576. push.apply(args, models);
  577. splice.apply(this.models, args);
  578. // Silently sort the collection if appropriate.
  579. needsSort = needsSort && this.comparator && at == null;
  580. if (needsSort) this.sort({silent: true});
  581. if (options.silent) return this;
  582. // Trigger `add` events.
  583. while (model = models.shift()) {
  584. model.trigger('add', model, this, options);
  585. }
  586. // Trigger `sort` if the collection was sorted.
  587. if (needsSort) this.trigger('sort', this, options);
  588. return this;
  589. },
  590. // Remove a model, or a list of models from the set. Pass silent to avoid
  591. // firing the `remove` event for every model removed.
  592. remove: function(models, options) {
  593. options || (options = {});
  594. models = _.isArray(models) ? models.slice() : [models];
  595. var i, l, index, model;
  596. for (i = 0, l = models.length; i < l; i++) {
  597. model = this.get(models[i]);
  598. if (!model) continue;
  599. delete this._byId[model.id];
  600. delete this._byId[model.cid];
  601. index = this.indexOf(model);
  602. this.models.splice(index, 1);
  603. this.length--;
  604. if (!options.silent) {
  605. options.index = index;
  606. model.trigger('remove', model, this, options);
  607. }
  608. this._removeReference(model);
  609. }
  610. return this;
  611. },
  612. // Add a model to the end of the collection.
  613. push: function(model, options) {
  614. model = this._prepareModel(model, options);
  615. this.add(model, _.extend({at: this.length}, options));
  616. return model;
  617. },
  618. // Remove a model from the end of the collection.
  619. pop: function(options) {
  620. var model = this.at(this.length - 1);
  621. this.remove(model, options);
  622. return model;
  623. },
  624. // Add a model to the beginning of the collection.
  625. unshift: function(model, options) {
  626. model = this._prepareModel(model, options);
  627. this.add(model, _.extend({at: 0}, options));
  628. return model;
  629. },
  630. // Remove a model from the beginning of the collection.
  631. shift: function(options) {
  632. var model = this.at(0);
  633. this.remove(model, options);
  634. return model;
  635. },
  636. // Slice out a sub-array of models from the collection.
  637. slice: function(begin, end) {
  638. return this.models.slice(begin, end);
  639. },
  640. // Get a model from the set by id.
  641. get: function(obj) {
  642. if (obj == null) return void 0;
  643. this._idAttr || (this._idAttr = this.model.prototype.idAttribute);
  644. return this._byId[obj.id || obj.cid || obj[this._idAttr] || obj];
  645. },
  646. // Get the model at the given index.
  647. at: function(index) {
  648. return this.models[index];
  649. },
  650. // Return models with matching attributes. Useful for simple cases of `filter`.
  651. where: function(attrs) {
  652. if (_.isEmpty(attrs)) return [];
  653. return this.filter(function(model) {
  654. for (var key in attrs) {
  655. if (attrs[key] !== model.get(key)) return false;
  656. }
  657. return true;
  658. });
  659. },
  660. // Force the collection to re-sort itself. You don't need to call this under
  661. // normal circumstances, as the set will maintain sort order as each item
  662. // is added.
  663. sort: function(options) {
  664. if (!this.comparator) {
  665. throw new Error('Cannot sort a set without a comparator');
  666. }
  667. options || (options = {});
  668. // Run sort based on type of `comparator`.
  669. if (_.isString(this.comparator) || this.comparator.length === 1) {
  670. this.models = this.sortBy(this.comparator, this);
  671. } else {
  672. this.models.sort(_.bind(this.comparator, this));
  673. }
  674. if (!options.silent) this.trigger('sort', this, options);
  675. return this;
  676. },
  677. // Pluck an attribute from each model in the collection.
  678. pluck: function(attr) {
  679. return _.invoke(this.models, 'get', attr);
  680. },
  681. // Smartly update a collection with a change set of models, adding,
  682. // removing, and merging as necessary.
  683. update: function(models, options) {
  684. options = _.extend({add: true, merge: true, remove: true}, options);
  685. if (options.parse) models = this.parse(models, options);
  686. var model, i, l, existing;
  687. var add = [], remove = [], modelMap = {};
  688. // Allow a single model (or no argument) to be passed.
  689. if (!_.isArray(models)) models = models ? [models] : [];
  690. // Proxy to `add` for this case, no need to iterate...
  691. if (options.add && !options.remove) return this.add(models, options);
  692. // Determine which models to add and merge, and which to remove.
  693. for (i = 0, l = models.length; i < l; i++) {
  694. model = models[i];
  695. existing = this.get(model);
  696. if (options.remove && existing) modelMap[existing.cid] = true;
  697. if ((options.add && !existing) || (options.merge && existing)) {
  698. add.push(model);
  699. }
  700. }
  701. if (options.remove) {
  702. for (i = 0, l = this.models.length; i < l; i++) {
  703. model = this.models[i];
  704. if (!modelMap[model.cid]) remove.push(model);
  705. }
  706. }
  707. // Remove models (if applicable) before we add and merge the rest.
  708. if (remove.length) this.remove(remove, options);
  709. if (add.length) this.add(add, options);
  710. return this;
  711. },
  712. // When you have more items than you want to add or remove individually,
  713. // you can reset the entire set with a new list of models, without firing
  714. // any `add` or `remove` events. Fires `reset` when finished.
  715. reset: function(models, options) {
  716. options || (options = {});
  717. if (options.parse) models = this.parse(models, options);
  718. for (var i = 0, l = this.models.length; i < l; i++) {
  719. this._removeReference(this.models[i]);
  720. }
  721. options.previousModels = this.models;
  722. this._reset();
  723. if (models) this.add(models, _.extend({silent: true}, options));
  724. if (!options.silent) this.trigger('reset', this, options);
  725. return this;
  726. },
  727. // Fetch the default set of models for this collection, resetting the
  728. // collection when they arrive. If `add: true` is passed, appends the
  729. // models to the collection instead of resetting.
  730. fetch: function(options) {
  731. options = options ? _.clone(options) : {};
  732. if (options.parse === void 0) options.parse = true;
  733. var collection = this;
  734. var success = options.success;
  735. options.success = function(resp, status, xhr) {
  736. var method = options.update ? 'update' : 'reset';
  737. collection[method](resp, options);
  738. if (success) success(collection, resp, options);
  739. };
  740. return this.sync('read', this, options);
  741. },
  742. // Create a new instance of a model in this collection. Add the model to the
  743. // collection immediately, unless `wait: true` is passed, in which case we
  744. // wait for the server to agree.
  745. create: function(model, options) {
  746. options = options ? _.clone(options) : {};
  747. model = this._prepareModel(model, options);
  748. var collection = this;
  749. if (!model) return false;
  750. if (!options.wait) collection.add(model, options);
  751. var success = options.success;
  752. options.success = function(model, resp, options) {
  753. if (options.wait) collection.add(model, options);
  754. if (success) success(model, resp, options);
  755. };
  756. model.save(null, options);
  757. return model;
  758. },
  759. // **parse** converts a response into a list of models to be added to the
  760. // collection. The default implementation is just to pass it through.
  761. parse: function(resp, options) {
  762. return resp;
  763. },
  764. // Create a new collection with an identical list of models as this one.
  765. clone: function() {
  766. return new this.constructor(this.models);
  767. },
  768. // Proxy to _'s chain. Can't be proxied the same way the rest of the
  769. // underscore methods are proxied because it relies on the underscore
  770. // constructor.
  771. chain: function() {
  772. return _(this.models).chain();
  773. },
  774. // Reset all internal state. Called when the collection is reset.
  775. _reset: function() {
  776. this.length = 0;
  777. this.models = [];
  778. this._byId = {};
  779. },
  780. // Prepare a model or hash of attributes to be added to this collection.
  781. _prepareModel: function(attrs, options) {
  782. if (attrs instanceof Model) {
  783. if (!attrs.collection) attrs.collection = this;
  784. return attrs;
  785. }
  786. options || (options = {});
  787. options.collection = this;
  788. var model = new this.model(attrs, options);
  789. if (!model._validate(attrs, options)) return false;
  790. return model;
  791. },
  792. // Internal method to remove a model's ties to a collection.
  793. _removeReference: function(model) {
  794. if (this === model.collection) delete model.collection;
  795. model.off('all', this._onModelEvent, this);
  796. },
  797. // Internal method called every time a model in the set fires an event.
  798. // Sets need to update their indexes when models change ids. All other
  799. // events simply proxy through. "add" and "remove" events that originate
  800. // in other collections are ignored.
  801. _onModelEvent: function(event, model, collection, options) {
  802. if ((event === 'add' || event === 'remove') && collection !== this) return;
  803. if (event === 'destroy') this.remove(model, options);
  804. if (model && event === 'change:' + model.idAttribute) {
  805. delete this._byId[model.previous(model.idAttribute)];
  806. if (model.id != null) this._byId[model.id] = model;
  807. }
  808. this.trigger.apply(this, arguments);
  809. }
  810. });
  811. // Underscore methods that we want to implement on the Collection.
  812. var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
  813. 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
  814. 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
  815. 'max', 'min', 'sortedIndex', 'toArray', 'size', 'first', 'head', 'take',
  816. 'initial', 'rest', 'tail', 'last', 'without', 'indexOf', 'shuffle',
  817. 'lastIndexOf', 'isEmpty'];
  818. // Mix in each Underscore method as a proxy to `Collection#models`.
  819. _.each(methods, function(method) {
  820. Collection.prototype[method] = function() {
  821. var args = slice.call(arguments);
  822. args.unshift(this.models);
  823. return _[method].apply(_, args);
  824. };
  825. });
  826. // Underscore methods that take a property name as an argument.
  827. var attributeMethods = ['groupBy', 'countBy', 'sortBy'];
  828. // Use attributes instead of properties.
  829. _.each(attributeMethods, function(method) {
  830. Collection.prototype[method] = function(value, context) {
  831. var iterator = _.isFunction(value) ? value : function(model) {
  832. return model.get(value);
  833. };
  834. return _[method](this.models, iterator, context);
  835. };
  836. });
  837. // Backbone.Router
  838. // ---------------
  839. // Routers map faux-URLs to actions, and fire events when routes are
  840. // matched. Creating a new one sets its `routes` hash, if not set statically.
  841. var Router = Backbone.Router = function(options) {
  842. options || (options = {});
  843. if (options.routes) this.routes = options.routes;
  844. this._bindRoutes();
  845. this.initialize.apply(this, arguments);
  846. };
  847. // Cached regular expressions for matching named param parts and splatted
  848. // parts of route strings.
  849. var optionalParam = /\((.*?)\)/g;
  850. var namedParam = /:\w+/g;
  851. var splatParam = /\*\w+/g;
  852. var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
  853. // Set up all inheritable **Backbone.Router** properties and methods.
  854. _.extend(Router.prototype, Events, {
  855. // Initialize is an empty function by default. Override it with your own
  856. // initialization logic.
  857. initialize: function(){},
  858. // Manually bind a single named route to a callback. For example:
  859. //
  860. // this.route('search/:query/p:num', 'search', function(query, num) {
  861. // ...
  862. // });
  863. //
  864. route: function(route, name, callback) {
  865. if (!_.isRegExp(route)) route = this._routeToRegExp(route);
  866. if (!callback) callback = this[name];
  867. Backbone.history.route(route, _.bind(function(fragment) {
  868. var args = this._extractParameters(route, fragment);
  869. callback && callback.apply(this, args);
  870. this.trigger.apply(this, ['route:' + name].concat(args));
  871. Backbone.history.trigger('route', this, name, args);
  872. }, this));
  873. return this;
  874. },
  875. // Simple proxy to `Backbone.history` to save a fragment into the history.
  876. navigate: function(fragment, options) {
  877. Backbone.history.navigate(fragment, options);
  878. return this;
  879. },
  880. // Bind all defined routes to `Backbone.history`. We have to reverse the
  881. // order of the routes here to support behavior where the most general
  882. // routes can be defined at the bottom of the route map.
  883. _bindRoutes: function() {
  884. if (!this.routes) return;
  885. var route, routes = _.keys(this.routes);
  886. while ((route = routes.pop()) != null) {
  887. this.route(route, this.routes[route]);
  888. }
  889. },
  890. // Convert a route string into a regular expression, suitable for matching
  891. // against the current location hash.
  892. _routeToRegExp: function(route) {
  893. route = route.replace(escapeRegExp, '\\$&')
  894. .replace(optionalParam, '(?:$1)?')
  895. .replace(namedParam, '([^\/]+)')
  896. .replace(splatParam, '(.*?)');
  897. return new RegExp('^' + route + '$');
  898. },
  899. // Given a route, and a URL fragment that it matches, return the array of
  900. // extracted parameters.
  901. _extractParameters: function(route, fragment) {
  902. return route.exec(fragment).slice(1);
  903. }
  904. });
  905. // Backbone.History
  906. // ----------------
  907. // Handles cross-browser history management, based on URL fragments. If the
  908. // browser does not support `onhashchange`, falls back to polling.
  909. var History = Backbone.History = function() {
  910. this.handlers = [];
  911. _.bindAll(this, 'checkUrl');
  912. // Ensure that `History` can be used outside of the browser.
  913. if (typeof window !== 'undefined') {
  914. this.location = window.location;
  915. this.history = window.history;
  916. }
  917. };
  918. // Cached regex for stripping a leading hash/slash and trailing space.
  919. var routeStripper = /^[#\/]|\s+$/g;
  920. // Cached regex for stripping leading and trailing slashes.
  921. var rootStripper = /^\/+|\/+$/g;
  922. // Cached regex for detecting MSIE.
  923. var isExplorer = /msie [\w.]+/;
  924. // Cached regex for removing a trailing slash.
  925. var trailingSlash = /\/$/;
  926. // Has the history handling already been started?
  927. History.started = false;
  928. // Set up all inheritable **Backbone.History** properties and methods.
  929. _.extend(History.prototype, Events, {
  930. // The default interval to poll for hash changes, if necessary, is
  931. // twenty times a second.
  932. interval: 50,
  933. // Gets the true hash value. Cannot use location.hash directly due to bug
  934. // in Firefox where location.hash will always be decoded.
  935. getHash: function(window) {
  936. var match = (window || this).location.href.match(/#(.*)$/);
  937. return match ? match[1] : '';
  938. },
  939. // Get the cross-browser normalized URL fragment, either from the URL,
  940. // the hash, or the override.
  941. getFragment: function(fragment, forcePushState) {
  942. if (fragment == null) {
  943. if (this._hasPushState || !this._wantsHashChange || forcePushState) {
  944. fragment = this.location.pathname;
  945. var root = this.root.replace(trailingSlash, '');
  946. if (!fragment.indexOf(root)) fragment = fragment.substr(root.length);
  947. } else {
  948. fragment = this.getHash();
  949. }
  950. }
  951. return fragment.replace(routeStripper, '');
  952. },
  953. // Start the hash change handling, returning `true` if the current URL matches
  954. // an existing route, and `false` otherwise.
  955. start: function(options) {
  956. if (History.started) throw new Error("Backbone.history has already been started");
  957. History.started = true;
  958. // Figure out the initial configuration. Do we need an iframe?
  959. // Is pushState desired ... is it available?
  960. this.options = _.extend({}, {root: '/'}, this.options, options);
  961. this.root = this.options.root;
  962. this._wantsHashChange = this.options.hashChange !== false;
  963. this._wantsPushState = !!this.options.pushState;
  964. this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
  965. var fragment = this.getFragment();
  966. var docMode = document.documentMode;
  967. var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
  968. // Normalize root to always include a leading and trailing slash.
  969. this.root = ('/' + this.root + '/').replace(rootStripper, '/');
  970. if (oldIE && this._wantsHashChange) {
  971. this.iframe = Backbone.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
  972. this.navigate(fragment);
  973. }
  974. // Depending on whether we're using pushState or hashes, and whether
  975. // 'onhashchange' is supported, determine how we check the URL state.
  976. if (this._hasPushState) {
  977. Backbone.$(window).bind('popstate', this.checkUrl);
  978. } else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
  979. Backbone.$(window).bind('hashchange', this.checkUrl);
  980. } else if (this._wantsHashChange) {
  981. this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
  982. }
  983. // Determine if we need to change the base url, for a pushState link
  984. // opened by a non-pushState browser.
  985. this.fragment = fragment;
  986. var loc = this.location;
  987. var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;
  988. // If we've started off with a route from a `pushState`-enabled browser,
  989. // but we're currently in a browser that doesn't support it...
  990. if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) {
  991. this.fragment = this.getFragment(null, true);
  992. this.location.replace(this.root + this.location.search + '#' + this.fragment);
  993. // Return immediately as browser will do redirect to new url
  994. return true;
  995. // Or if we've started out with a hash-based route, but we're currently
  996. // in a browser where it could be `pushState`-based instead...
  997. } else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
  998. this.fragment = this.getHash().replace(routeStripper, '');
  999. this.history.replaceState({}, document.title, this.root + this.fragment + loc.search);
  1000. }
  1001. if (!this.options.silent) return this.loadUrl();
  1002. },
  1003. // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
  1004. // but possibly useful for unit testing Routers.
  1005. stop: function() {
  1006. Backbone.$(window).unbind('popstate', this.checkUrl).unbind('hashchange', this.checkUrl);
  1007. clearInterval(this._checkUrlInterval);
  1008. History.started = false;
  1009. },
  1010. // Add a route to be tested when the fragment changes. Routes added later
  1011. // may override previous routes.
  1012. route: function(route, callback) {
  1013. this.handlers.unshift({route: route, callback: callback});
  1014. },
  1015. // Checks the current URL to see if it has changed, and if it has,
  1016. // calls `loadUrl`, normalizing across the hidden iframe.
  1017. checkUrl: function(e) {
  1018. var current = this.getFragment();
  1019. if (current === this.fragment && this.iframe) {
  1020. current = this.getFragment(this.getHash(this.iframe));
  1021. }
  1022. if (current === this.fragment) return false;
  1023. if (this.iframe) this.navigate(current);
  1024. this.loadUrl() || this.loadUrl(this.getHash());
  1025. },
  1026. // Attempt to load the current URL fragment. If a route succeeds with a
  1027. // match, returns `true`. If no defined routes matches the fragment,
  1028. // returns `false`.
  1029. loadUrl: function(fragmentOverride) {
  1030. var fragment = this.fragment = this.getFragment(fragmentOverride);
  1031. var matched = _.any(this.handlers, function(handler) {
  1032. if (handler.route.test(fragment)) {
  1033. handler.callback(fragment);
  1034. return true;
  1035. }
  1036. });
  1037. return matched;
  1038. },
  1039. // Save a fragment into the hash history, or replace the URL state if the
  1040. // 'replace' option is passed. You are responsible for properly URL-encoding
  1041. // the fragment in advance.
  1042. //
  1043. // The options object can contain `trigger: true` if you wish to have the
  1044. // route callback be fired (not usually desirable), or `replace: true`, if
  1045. // you wish to modify the current URL without adding an entry to the history.
  1046. navigate: function(fragment, options) {
  1047. if (!History.started) return false;
  1048. if (!options || options === true) options = {trigger: options};
  1049. fragment = this.getFragment(fragment || '');
  1050. if (this.fragment === fragment) return;
  1051. this.fragment = fragment;
  1052. var url = this.root + fragment;
  1053. // If pushState is available, we use it to set the fragment as a real URL.
  1054. if (this._hasPushState) {
  1055. this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
  1056. // If hash changes haven't been explicitly disabled, update the hash
  1057. // fragment to store history.
  1058. } else if (this._wantsHashChange) {
  1059. this._updateHash(this.location, fragment, options.replace);
  1060. if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) {
  1061. // Opening and closing the iframe tricks IE7 and earlier to push a
  1062. // history entry on hash-tag change. When replace is true, we don't
  1063. // want this.
  1064. if(!options.replace) this.iframe.document.open().close();
  1065. this._updateHash(this.iframe.location, fragment, options.replace);
  1066. }
  1067. // If you've told us that you explicitly don't want fallback hashchange-
  1068. // based history, then `navigate` becomes a page refresh.
  1069. } else {
  1070. return this.location.assign(url);
  1071. }
  1072. if (options.trigger) this.loadUrl(fragment);
  1073. },
  1074. // Update the hash location, either replacing the current entry, or adding
  1075. // a new one to the browser history.
  1076. _updateHash: function(location, fragment, replace) {
  1077. if (replace) {
  1078. var href = location.href.replace(/(javascript:|#).*$/, '');
  1079. location.replace(href + '#' + fragment);
  1080. } else {
  1081. // Some browsers require that `hash` contains a leading #.
  1082. location.hash = '#' + fragment;
  1083. }
  1084. }
  1085. });
  1086. // Create the default Backbone.history.
  1087. Backbone.history = new History;
  1088. // Backbone.View
  1089. // -------------
  1090. // Creating a Backbone.View creates its initial element outside of the DOM,
  1091. // if an existing element is not provided...
  1092. var View = Backbone.View = function(options) {
  1093. this.cid = _.uniqueId('view');
  1094. this._configure(options || {});
  1095. this._ensureElement();
  1096. this.initialize.apply(this, arguments);
  1097. this.delegateEvents();
  1098. };
  1099. // Cached regex to split keys for `delegate`.
  1100. var delegateEventSplitter = /^(\S+)\s*(.*)$/;
  1101. // List of view options to be merged as properties.
  1102. var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
  1103. // Set up all inheritable **Backbone.View** properties and methods.
  1104. _.extend(View.prototype, Events, {
  1105. // The default `tagName` of a View's element is `"div"`.
  1106. tagName: 'div',
  1107. // jQuery delegate for element lookup, scoped to DOM elements within the
  1108. // current view. This should be prefered to global lookups where possible.
  1109. $: function(selector) {
  1110. return this.$el.find(selector);
  1111. },
  1112. // Initialize is an empty function by default. Override it with your own
  1113. // initialization logic.
  1114. initialize: function(){},
  1115. // **render** is the core function that your view should override, in order
  1116. // to populate its element (`this.el`), with the appropriate HTML. The
  1117. // convention is for **render** to always return `this`.
  1118. render: function() {
  1119. return this;
  1120. },
  1121. // Remove this view by taking the element out of the DOM, and removing any
  1122. // applicable Backbone.Events listeners.
  1123. remove: function() {
  1124. this.$el.remove();
  1125. this.stopListening();
  1126. return this;
  1127. },
  1128. // For small amounts of DOM Elements, where a full-blown template isn't
  1129. // needed, use **make** to manufacture elements, one at a time.
  1130. //
  1131. // var el = this.make('li', {'class': 'row'}, this.model.escape('title'));
  1132. //
  1133. make: function(tagName, attributes, content) {
  1134. var el = document.createElement(tagName);
  1135. if (attributes) Backbone.$(el).attr(attributes);
  1136. if (content != null) Backbone.$(el).html(content);
  1137. return el;
  1138. },
  1139. // Change the view's element (`this.el` property), including event
  1140. // re-delegation.
  1141. setElement: function(element, delegate) {
  1142. if (this.$el) this.undelegateEvents();
  1143. this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
  1144. this.el = this.$el[0];
  1145. if (delegate !== false) this.delegateEvents();
  1146. return this;
  1147. },
  1148. // Set callbacks, where `this.events` is a hash of
  1149. //
  1150. // *{"event selector": "callback"}*
  1151. //
  1152. // {
  1153. // 'mousedown .title': 'edit',
  1154. // 'click .button': 'save'
  1155. // 'click .…

Large files files are truncated, but you can click here to view the full file