PageRenderTime 56ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/ch12/backbone.js

http://github.com/maccman/book-assets
JavaScript | 1085 lines | 655 code | 143 blank | 287 comment | 199 complexity | bb4883ac1218c5bf561db787bb088fba MD5 | raw file
Possible License(s): JSON
  1. // Backbone.js 0.3.3
  2. // (c) 2010 Jeremy Ashkenas, DocumentCloud Inc.
  3. // Backbone may be freely distributed under the MIT license.
  4. // For all details and documentation:
  5. // http://documentcloud.github.com/backbone
  6. (function(){
  7. // Initial Setup
  8. // -------------
  9. // The top-level namespace. All public Backbone classes and modules will
  10. // be attached to this. Exported for both CommonJS and the browser.
  11. var Backbone;
  12. if (typeof exports !== 'undefined') {
  13. Backbone = exports;
  14. } else {
  15. Backbone = this.Backbone = {};
  16. }
  17. // Current version of the library. Keep in sync with `package.json`.
  18. Backbone.VERSION = '0.3.3';
  19. // Require Underscore, if we're on the server, and it's not already present.
  20. var _ = this._;
  21. if (!_ && (typeof require !== 'undefined')) _ = require('underscore')._;
  22. // For Backbone's purposes, either jQuery or Zepto owns the `$` variable.
  23. var $ = this.jQuery || this.Zepto;
  24. // Turn on `emulateHTTP` to use support legacy HTTP servers. Setting this option will
  25. // fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and set a
  26. // `X-Http-Method-Override` header.
  27. Backbone.emulateHTTP = false;
  28. // Turn on `emulateJSON` to support legacy servers that can't deal with direct
  29. // `application/json` requests ... will encode the body as
  30. // `application/x-www-form-urlencoded` instead and will send the model in a
  31. // form param named `model`.
  32. Backbone.emulateJSON = false;
  33. // Backbone.Events
  34. // -----------------
  35. // A module that can be mixed in to *any object* in order to provide it with
  36. // custom events. You may `bind` or `unbind` a callback function to an event;
  37. // `trigger`-ing an event fires all callbacks in succession.
  38. //
  39. // var object = {};
  40. // _.extend(object, Backbone.Events);
  41. // object.bind('expand', function(){ alert('expanded'); });
  42. // object.trigger('expand');
  43. //
  44. Backbone.Events = {
  45. // Bind an event, specified by a string name, `ev`, to a `callback` function.
  46. // Passing `"all"` will bind the callback to all events fired.
  47. bind : function(ev, callback) {
  48. var calls = this._callbacks || (this._callbacks = {});
  49. var list = this._callbacks[ev] || (this._callbacks[ev] = []);
  50. list.push(callback);
  51. return this;
  52. },
  53. // Remove one or many callbacks. If `callback` is null, removes all
  54. // callbacks for the event. If `ev` is null, removes all bound callbacks
  55. // for all events.
  56. unbind : function(ev, callback) {
  57. var calls;
  58. if (!ev) {
  59. this._callbacks = {};
  60. } else if (calls = this._callbacks) {
  61. if (!callback) {
  62. calls[ev] = [];
  63. } else {
  64. var list = calls[ev];
  65. if (!list) return this;
  66. for (var i = 0, l = list.length; i < l; i++) {
  67. if (callback === list[i]) {
  68. list.splice(i, 1);
  69. break;
  70. }
  71. }
  72. }
  73. }
  74. return this;
  75. },
  76. // Trigger an event, firing all bound callbacks. Callbacks are passed the
  77. // same arguments as `trigger` is, apart from the event name.
  78. // Listening for `"all"` passes the true event name as the first argument.
  79. trigger : function(ev) {
  80. var list, calls, i, l;
  81. if (!(calls = this._callbacks)) return this;
  82. if (calls[ev]) {
  83. list = calls[ev].slice(0);
  84. for (i = 0, l = list.length; i < l; i++) {
  85. list[i].apply(this, Array.prototype.slice.call(arguments, 1));
  86. }
  87. }
  88. if (calls['all']) {
  89. list = calls['all'].slice(0);
  90. for (i = 0, l = list.length; i < l; i++) {
  91. list[i].apply(this, arguments);
  92. }
  93. }
  94. return this;
  95. }
  96. };
  97. // Backbone.Model
  98. // --------------
  99. // Create a new model, with defined attributes. A client id (`cid`)
  100. // is automatically generated and assigned for you.
  101. Backbone.Model = function(attributes, options) {
  102. var defaults;
  103. attributes || (attributes = {});
  104. if (defaults = this.defaults) {
  105. if (_.isFunction(defaults)) defaults = defaults();
  106. attributes = _.extend({}, defaults, attributes);
  107. }
  108. this.attributes = {};
  109. this._escapedAttributes = {};
  110. this.cid = _.uniqueId('c');
  111. this.set(attributes, {silent : true});
  112. this._changed = false;
  113. this._previousAttributes = _.clone(this.attributes);
  114. if (options && options.collection) this.collection = options.collection;
  115. this.initialize(attributes, options);
  116. };
  117. // Attach all inheritable methods to the Model prototype.
  118. _.extend(Backbone.Model.prototype, Backbone.Events, {
  119. // A snapshot of the model's previous attributes, taken immediately
  120. // after the last `"change"` event was fired.
  121. _previousAttributes : null,
  122. // Has the item been changed since the last `"change"` event?
  123. _changed : false,
  124. // The default name for the JSON `id` attribute is `"id"`. MongoDB and
  125. // CouchDB users may want to set this to `"_id"`.
  126. idAttribute : 'id',
  127. // Initialize is an empty function by default. Override it with your own
  128. // initialization logic.
  129. initialize : function(){},
  130. // Return a copy of the model's `attributes` object.
  131. toJSON : function() {
  132. return _.clone(this.attributes);
  133. },
  134. // Get the value of an attribute.
  135. get : function(attr) {
  136. return this.attributes[attr];
  137. },
  138. // Get the HTML-escaped value of an attribute.
  139. escape : function(attr) {
  140. var html;
  141. if (html = this._escapedAttributes[attr]) return html;
  142. var val = this.attributes[attr];
  143. return this._escapedAttributes[attr] = escapeHTML(val == null ? '' : '' + val);
  144. },
  145. // Returns `true` if the attribute contains a value that is not null
  146. // or undefined.
  147. has : function(attr) {
  148. return this.attributes[attr] != null;
  149. },
  150. // Set a hash of model attributes on the object, firing `"change"` unless you
  151. // choose to silence it.
  152. set : function(attrs, options) {
  153. // Extract attributes and options.
  154. options || (options = {});
  155. if (!attrs) return this;
  156. if (attrs.attributes) attrs = attrs.attributes;
  157. var now = this.attributes, escaped = this._escapedAttributes;
  158. // Run validation.
  159. if (!options.silent && this.validate && !this._performValidation(attrs, options)) return false;
  160. // Check for changes of `id`.
  161. if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
  162. // Update attributes.
  163. for (var attr in attrs) {
  164. var val = attrs[attr];
  165. if (!_.isEqual(now[attr], val)) {
  166. now[attr] = val;
  167. delete escaped[attr];
  168. this._changed = true;
  169. if (!options.silent) this.trigger('change:' + attr, this, val, options);
  170. }
  171. }
  172. // Fire the `"change"` event, if the model has been changed.
  173. if (!options.silent && this._changed) this.change(options);
  174. return this;
  175. },
  176. // Remove an attribute from the model, firing `"change"` unless you choose
  177. // to silence it. `unset` is a noop if the attribute doesn't exist.
  178. unset : function(attr, options) {
  179. if (!(attr in this.attributes)) return this;
  180. options || (options = {});
  181. var value = this.attributes[attr];
  182. // Run validation.
  183. var validObj = {};
  184. validObj[attr] = void 0;
  185. if (!options.silent && this.validate && !this._performValidation(validObj, options)) return false;
  186. // Remove the attribute.
  187. delete this.attributes[attr];
  188. delete this._escapedAttributes[attr];
  189. if (attr == this.idAttribute) delete this.id;
  190. this._changed = true;
  191. if (!options.silent) {
  192. this.trigger('change:' + attr, this, void 0, options);
  193. this.change(options);
  194. }
  195. return this;
  196. },
  197. // Clear all attributes on the model, firing `"change"` unless you choose
  198. // to silence it.
  199. clear : function(options) {
  200. options || (options = {});
  201. var old = this.attributes;
  202. // Run validation.
  203. var validObj = {};
  204. for (attr in old) validObj[attr] = void 0;
  205. if (!options.silent && this.validate && !this._performValidation(validObj, options)) return false;
  206. this.attributes = {};
  207. this._escapedAttributes = {};
  208. this._changed = true;
  209. if (!options.silent) {
  210. for (attr in old) {
  211. this.trigger('change:' + attr, this, void 0, options);
  212. }
  213. this.change(options);
  214. }
  215. return this;
  216. },
  217. // Fetch the model from the server. If the server's representation of the
  218. // model differs from its current attributes, they will be overriden,
  219. // triggering a `"change"` event.
  220. fetch : function(options) {
  221. options || (options = {});
  222. var model = this;
  223. var success = options.success;
  224. options.success = function(resp) {
  225. if (!model.set(model.parse(resp), options)) return false;
  226. if (success) success(model, resp);
  227. };
  228. options.error = wrapError(options.error, model, options);
  229. (this.sync || Backbone.sync).call(this, 'read', this, options);
  230. return this;
  231. },
  232. // Set a hash of model attributes, and sync the model to the server.
  233. // If the server returns an attributes hash that differs, the model's
  234. // state will be `set` again.
  235. save : function(attrs, options) {
  236. options || (options = {});
  237. if (attrs && !this.set(attrs, options)) return false;
  238. var model = this;
  239. var success = options.success;
  240. options.success = function(resp) {
  241. if (!model.set(model.parse(resp), options)) return false;
  242. if (success) success(model, resp);
  243. };
  244. options.error = wrapError(options.error, model, options);
  245. var method = this.isNew() ? 'create' : 'update';
  246. (this.sync || Backbone.sync).call(this, method, this, options);
  247. return this;
  248. },
  249. // Destroy this model on the server. Upon success, the model is removed
  250. // from its collection, if it has one.
  251. destroy : function(options) {
  252. options || (options = {});
  253. var model = this;
  254. var success = options.success;
  255. options.success = function(resp) {
  256. model.trigger('destroy', model, model.collection, options);
  257. if (success) success(model, resp);
  258. };
  259. options.error = wrapError(options.error, model, options);
  260. (this.sync || Backbone.sync).call(this, 'delete', this, options);
  261. return this;
  262. },
  263. // Default URL for the model's representation on the server -- if you're
  264. // using Backbone's restful methods, override this to change the endpoint
  265. // that will be called.
  266. url : function() {
  267. var base = getUrl(this.collection) || this.urlRoot || urlError();
  268. if (this.isNew()) return base;
  269. return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + encodeURIComponent(this.id);
  270. },
  271. // **parse** converts a response into the hash of attributes to be `set` on
  272. // the model. The default implementation is just to pass the response along.
  273. parse : function(resp) {
  274. return resp;
  275. },
  276. // Create a new model with identical attributes to this one.
  277. clone : function() {
  278. return new this.constructor(this);
  279. },
  280. // A model is new if it has never been saved to the server, and has a negative
  281. // ID.
  282. isNew : function() {
  283. return !this.id;
  284. },
  285. // Call this method to manually fire a `change` event for this model.
  286. // Calling this will cause all objects observing the model to update.
  287. change : function(options) {
  288. this.trigger('change', this, options);
  289. this._previousAttributes = _.clone(this.attributes);
  290. this._changed = false;
  291. },
  292. // Determine if the model has changed since the last `"change"` event.
  293. // If you specify an attribute name, determine if that attribute has changed.
  294. hasChanged : function(attr) {
  295. if (attr) return this._previousAttributes[attr] != this.attributes[attr];
  296. return this._changed;
  297. },
  298. // Return an object containing all the attributes that have changed, or false
  299. // if there are no changed attributes. Useful for determining what parts of a
  300. // view need to be updated and/or what attributes need to be persisted to
  301. // the server.
  302. changedAttributes : function(now) {
  303. now || (now = this.attributes);
  304. var old = this._previousAttributes;
  305. var changed = false;
  306. for (var attr in now) {
  307. if (!_.isEqual(old[attr], now[attr])) {
  308. changed = changed || {};
  309. changed[attr] = now[attr];
  310. }
  311. }
  312. return changed;
  313. },
  314. // Get the previous value of an attribute, recorded at the time the last
  315. // `"change"` event was fired.
  316. previous : function(attr) {
  317. if (!attr || !this._previousAttributes) return null;
  318. return this._previousAttributes[attr];
  319. },
  320. // Get all of the attributes of the model at the time of the previous
  321. // `"change"` event.
  322. previousAttributes : function() {
  323. return _.clone(this._previousAttributes);
  324. },
  325. // Run validation against a set of incoming attributes, returning `true`
  326. // if all is well. If a specific `error` callback has been passed,
  327. // call that instead of firing the general `"error"` event.
  328. _performValidation : function(attrs, options) {
  329. var error = this.validate(attrs);
  330. if (error) {
  331. if (options.error) {
  332. options.error(this, error);
  333. } else {
  334. this.trigger('error', this, error, options);
  335. }
  336. return false;
  337. }
  338. return true;
  339. }
  340. });
  341. // Backbone.Collection
  342. // -------------------
  343. // Provides a standard collection class for our sets of models, ordered
  344. // or unordered. If a `comparator` is specified, the Collection will maintain
  345. // its models in sort order, as they're added and removed.
  346. Backbone.Collection = function(models, options) {
  347. options || (options = {});
  348. if (options.comparator) {
  349. this.comparator = options.comparator;
  350. delete options.comparator;
  351. }
  352. _.bindAll(this, '_onModelEvent', '_removeReference');
  353. this._reset();
  354. if (models) this.refresh(models, {silent: true});
  355. this.initialize(models, options);
  356. };
  357. // Define the Collection's inheritable methods.
  358. _.extend(Backbone.Collection.prototype, Backbone.Events, {
  359. // The default model for a collection is just a **Backbone.Model**.
  360. // This should be overridden in most cases.
  361. model : Backbone.Model,
  362. // Initialize is an empty function by default. Override it with your own
  363. // initialization logic.
  364. initialize : function(){},
  365. // The JSON representation of a Collection is an array of the
  366. // models' attributes.
  367. toJSON : function() {
  368. return this.map(function(model){ return model.toJSON(); });
  369. },
  370. // Add a model, or list of models to the set. Pass **silent** to avoid
  371. // firing the `added` event for every new model.
  372. add : function(models, options) {
  373. if (_.isArray(models)) {
  374. for (var i = 0, l = models.length; i < l; i++) {
  375. this._add(models[i], options);
  376. }
  377. } else {
  378. this._add(models, options);
  379. }
  380. return this;
  381. },
  382. // Remove a model, or a list of models from the set. Pass silent to avoid
  383. // firing the `removed` event for every model removed.
  384. remove : function(models, options) {
  385. if (_.isArray(models)) {
  386. for (var i = 0, l = models.length; i < l; i++) {
  387. this._remove(models[i], options);
  388. }
  389. } else {
  390. this._remove(models, options);
  391. }
  392. return this;
  393. },
  394. // Get a model from the set by id.
  395. get : function(id) {
  396. if (id == null) return null;
  397. return this._byId[id.id != null ? id.id : id];
  398. },
  399. // Get a model from the set by client id.
  400. getByCid : function(cid) {
  401. return cid && this._byCid[cid.cid || cid];
  402. },
  403. // Get the model at the given index.
  404. at: function(index) {
  405. return this.models[index];
  406. },
  407. // Force the collection to re-sort itself. You don't need to call this under normal
  408. // circumstances, as the set will maintain sort order as each item is added.
  409. sort : function(options) {
  410. options || (options = {});
  411. if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
  412. this.models = this.sortBy(this.comparator);
  413. if (!options.silent) this.trigger('refresh', this, options);
  414. return this;
  415. },
  416. // Pluck an attribute from each model in the collection.
  417. pluck : function(attr) {
  418. return _.map(this.models, function(model){ return model.get(attr); });
  419. },
  420. // When you have more items than you want to add or remove individually,
  421. // you can refresh the entire set with a new list of models, without firing
  422. // any `added` or `removed` events. Fires `refresh` when finished.
  423. refresh : function(models, options) {
  424. models || (models = []);
  425. options || (options = {});
  426. this.each(this._removeReference);
  427. this._reset();
  428. this.add(models, {silent: true});
  429. if (!options.silent) this.trigger('refresh', this, options);
  430. return this;
  431. },
  432. // Fetch the default set of models for this collection, refreshing the
  433. // collection when they arrive. If `add: true` is passed, appends the
  434. // models to the collection instead of refreshing.
  435. fetch : function(options) {
  436. options || (options = {});
  437. var collection = this;
  438. var success = options.success;
  439. options.success = function(resp) {
  440. collection[options.add ? 'add' : 'refresh'](collection.parse(resp), options);
  441. if (success) success(collection, resp);
  442. };
  443. options.error = wrapError(options.error, collection, options);
  444. (this.sync || Backbone.sync).call(this, 'read', this, options);
  445. return this;
  446. },
  447. // Create a new instance of a model in this collection. After the model
  448. // has been created on the server, it will be added to the collection.
  449. create : function(model, options) {
  450. var coll = this;
  451. options || (options = {});
  452. if (!(model instanceof Backbone.Model)) {
  453. var attrs = model;
  454. model = new this.model(null, {collection: coll});
  455. if (!model.set(attrs)) return false;
  456. } else {
  457. model.collection = coll;
  458. }
  459. var success = options.success;
  460. options.success = function(nextModel, resp) {
  461. coll.add(nextModel);
  462. if (success) success(nextModel, resp);
  463. };
  464. return model.save(null, options);
  465. },
  466. // **parse** converts a response into a list of models to be added to the
  467. // collection. The default implementation is just to pass it through.
  468. parse : function(resp) {
  469. return resp;
  470. },
  471. // Proxy to _'s chain. Can't be proxied the same way the rest of the
  472. // underscore methods are proxied because it relies on the underscore
  473. // constructor.
  474. chain: function () {
  475. return _(this.models).chain();
  476. },
  477. // Reset all internal state. Called when the collection is refreshed.
  478. _reset : function(options) {
  479. this.length = 0;
  480. this.models = [];
  481. this._byId = {};
  482. this._byCid = {};
  483. },
  484. // Internal implementation of adding a single model to the set, updating
  485. // hash indexes for `id` and `cid` lookups.
  486. _add : function(model, options) {
  487. options || (options = {});
  488. if (!(model instanceof Backbone.Model)) {
  489. model = new this.model(model, {collection: this});
  490. }
  491. var already = this.getByCid(model);
  492. if (already) throw new Error(["Can't add the same model to a set twice", already.id]);
  493. this._byId[model.id] = model;
  494. this._byCid[model.cid] = model;
  495. if (!model.collection) {
  496. model.collection = this;
  497. }
  498. var index = this.comparator ? this.sortedIndex(model, this.comparator) : this.length;
  499. this.models.splice(index, 0, model);
  500. model.bind('all', this._onModelEvent);
  501. this.length++;
  502. if (!options.silent) model.trigger('add', model, this, options);
  503. return model;
  504. },
  505. // Internal implementation of removing a single model from the set, updating
  506. // hash indexes for `id` and `cid` lookups.
  507. _remove : function(model, options) {
  508. options || (options = {});
  509. model = this.getByCid(model) || this.get(model);
  510. if (!model) return null;
  511. delete this._byId[model.id];
  512. delete this._byCid[model.cid];
  513. this.models.splice(this.indexOf(model), 1);
  514. this.length--;
  515. if (!options.silent) model.trigger('remove', model, this, options);
  516. this._removeReference(model);
  517. return model;
  518. },
  519. // Internal method to remove a model's ties to a collection.
  520. _removeReference : function(model) {
  521. if (this == model.collection) {
  522. delete model.collection;
  523. }
  524. model.unbind('all', this._onModelEvent);
  525. },
  526. // Internal method called every time a model in the set fires an event.
  527. // Sets need to update their indexes when models change ids. All other
  528. // events simply proxy through. "add" and "remove" events that originate
  529. // in other collections are ignored.
  530. _onModelEvent : function(ev, model, collection, options) {
  531. if ((ev == 'add' || ev == 'remove') && collection != this) return;
  532. if (ev == 'destroy') {
  533. this._remove(model, options);
  534. }
  535. if (ev === 'change:' + model.idAttribute) {
  536. delete this._byId[model.previous(model.idAttribute)];
  537. this._byId[model.id] = model;
  538. }
  539. this.trigger.apply(this, arguments);
  540. }
  541. });
  542. // Underscore methods that we want to implement on the Collection.
  543. var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find', 'detect',
  544. 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include',
  545. 'invoke', 'max', 'min', 'sortBy', 'sortedIndex', 'toArray', 'size',
  546. 'first', 'rest', 'last', 'without', 'indexOf', 'lastIndexOf', 'isEmpty'];
  547. // Mix in each Underscore method as a proxy to `Collection#models`.
  548. _.each(methods, function(method) {
  549. Backbone.Collection.prototype[method] = function() {
  550. return _[method].apply(_, [this.models].concat(_.toArray(arguments)));
  551. };
  552. });
  553. // Backbone.Controller
  554. // -------------------
  555. // Controllers map faux-URLs to actions, and fire events when routes are
  556. // matched. Creating a new one sets its `routes` hash, if not set statically.
  557. Backbone.Controller = function(options) {
  558. options || (options = {});
  559. if (options.routes) this.routes = options.routes;
  560. this._bindRoutes();
  561. this.initialize(options);
  562. };
  563. // Cached regular expressions for matching named param parts and splatted
  564. // parts of route strings.
  565. var namedParam = /:([\w\d]+)/g;
  566. var splatParam = /\*([\w\d]+)/g;
  567. var escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g;
  568. // Set up all inheritable **Backbone.Controller** properties and methods.
  569. _.extend(Backbone.Controller.prototype, Backbone.Events, {
  570. // Initialize is an empty function by default. Override it with your own
  571. // initialization logic.
  572. initialize : function(){},
  573. // Manually bind a single named route to a callback. For example:
  574. //
  575. // this.route('search/:query/p:num', 'search', function(query, num) {
  576. // ...
  577. // });
  578. //
  579. route : function(route, name, callback) {
  580. Backbone.history || (Backbone.history = new Backbone.History);
  581. if (!_.isRegExp(route)) route = this._routeToRegExp(route);
  582. Backbone.history.route(route, _.bind(function(fragment) {
  583. var args = this._extractParameters(route, fragment);
  584. callback.apply(this, args);
  585. this.trigger.apply(this, ['route:' + name].concat(args));
  586. }, this));
  587. },
  588. // Simple proxy to `Backbone.history` to save a fragment into the history,
  589. // without triggering routes.
  590. saveLocation : function(fragment) {
  591. Backbone.history.saveLocation(fragment);
  592. },
  593. // Bind all defined routes to `Backbone.history`. We have to reverse the
  594. // order of the routes here to support behavior where the most general
  595. // routes can be defined at the bottom of the route map.
  596. _bindRoutes : function() {
  597. if (!this.routes) return;
  598. var routes = [];
  599. for (var route in this.routes) {
  600. routes.unshift([route, this.routes[route]]);
  601. }
  602. for (var i = 0, l = routes.length; i < l; i++) {
  603. this.route(routes[i][0], routes[i][1], this[routes[i][1]]);
  604. }
  605. },
  606. // Convert a route string into a regular expression, suitable for matching
  607. // against the current location fragment.
  608. _routeToRegExp : function(route) {
  609. route = route.replace(escapeRegExp, "\\$&")
  610. .replace(namedParam, "([^\/]*)")
  611. .replace(splatParam, "(.*?)");
  612. return new RegExp('^' + route + '$');
  613. },
  614. // Given a route, and a URL fragment that it matches, return the array of
  615. // extracted parameters.
  616. _extractParameters : function(route, fragment) {
  617. return route.exec(fragment).slice(1);
  618. }
  619. });
  620. // Backbone.History
  621. // ----------------
  622. // Handles cross-browser history management, based on URL hashes. If the
  623. // browser does not support `onhashchange`, falls back to polling.
  624. Backbone.History = function() {
  625. this.handlers = [];
  626. this.fragment = this.getFragment();
  627. _.bindAll(this, 'checkUrl');
  628. };
  629. // Cached regex for cleaning hashes.
  630. var hashStrip = /^#*/;
  631. // Has the history handling already been started?
  632. var historyStarted = false;
  633. // Set up all inheritable **Backbone.History** properties and methods.
  634. _.extend(Backbone.History.prototype, {
  635. // The default interval to poll for hash changes, if necessary, is
  636. // twenty times a second.
  637. interval: 50,
  638. // Get the cross-browser normalized URL fragment.
  639. getFragment : function(loc) {
  640. return (loc || window.location).hash.replace(hashStrip, '');
  641. },
  642. // Start the hash change handling, returning `true` if the current URL matches
  643. // an existing route, and `false` otherwise.
  644. start : function() {
  645. if (historyStarted) throw new Error("Backbone.history has already been started");
  646. var docMode = document.documentMode;
  647. var oldIE = ($.browser.msie && (!docMode || docMode <= 7));
  648. if (oldIE) {
  649. this.iframe = $('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
  650. }
  651. if ('onhashchange' in window && !oldIE) {
  652. $(window).bind('hashchange', this.checkUrl);
  653. } else {
  654. setInterval(this.checkUrl, this.interval);
  655. }
  656. historyStarted = true;
  657. return this.loadUrl();
  658. },
  659. // Add a route to be tested when the hash changes. Routes added later may
  660. // override previous routes.
  661. route : function(route, callback) {
  662. this.handlers.unshift({route : route, callback : callback});
  663. },
  664. // Checks the current URL to see if it has changed, and if it has,
  665. // calls `loadUrl`, normalizing across the hidden iframe.
  666. checkUrl : function() {
  667. var current = this.getFragment();
  668. if (current == this.fragment && this.iframe) {
  669. current = this.getFragment(this.iframe.location);
  670. }
  671. if (current == this.fragment ||
  672. current == decodeURIComponent(this.fragment)) return false;
  673. if (this.iframe) {
  674. window.location.hash = this.iframe.location.hash = current;
  675. }
  676. this.loadUrl();
  677. },
  678. // Attempt to load the current URL fragment. If a route succeeds with a
  679. // match, returns `true`. If no defined routes matches the fragment,
  680. // returns `false`.
  681. loadUrl : function() {
  682. var fragment = this.fragment = this.getFragment();
  683. var matched = _.any(this.handlers, function(handler) {
  684. if (handler.route.test(fragment)) {
  685. handler.callback(fragment);
  686. return true;
  687. }
  688. });
  689. return matched;
  690. },
  691. // Save a fragment into the hash history. You are responsible for properly
  692. // URL-encoding the fragment in advance. This does not trigger
  693. // a `hashchange` event.
  694. saveLocation : function(fragment) {
  695. fragment = (fragment || '').replace(hashStrip, '');
  696. if (this.fragment == fragment) return;
  697. window.location.hash = this.fragment = fragment;
  698. if (this.iframe && (fragment != this.getFragment(this.iframe.location))) {
  699. this.iframe.document.open().close();
  700. this.iframe.location.hash = fragment;
  701. }
  702. }
  703. });
  704. // Backbone.View
  705. // -------------
  706. // Creating a Backbone.View creates its initial element outside of the DOM,
  707. // if an existing element is not provided...
  708. Backbone.View = function(options) {
  709. this.cid = _.uniqueId('view');
  710. this._configure(options || {});
  711. this._ensureElement();
  712. this.delegateEvents();
  713. this.initialize(options);
  714. };
  715. // Element lookup, scoped to DOM elements within the current view.
  716. // This should be prefered to global lookups, if you're dealing with
  717. // a specific view.
  718. var selectorDelegate = function(selector) {
  719. return $(selector, this.el);
  720. };
  721. // Cached regex to split keys for `delegate`.
  722. var eventSplitter = /^(\w+)\s*(.*)$/;
  723. // List of view options to be merged as properties.
  724. var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName'];
  725. // Set up all inheritable **Backbone.View** properties and methods.
  726. _.extend(Backbone.View.prototype, Backbone.Events, {
  727. // The default `tagName` of a View's element is `"div"`.
  728. tagName : 'div',
  729. // Attach the `selectorDelegate` function as the `$` property.
  730. $ : selectorDelegate,
  731. // Initialize is an empty function by default. Override it with your own
  732. // initialization logic.
  733. initialize : function(){},
  734. // **render** is the core function that your view should override, in order
  735. // to populate its element (`this.el`), with the appropriate HTML. The
  736. // convention is for **render** to always return `this`.
  737. render : function() {
  738. return this;
  739. },
  740. // Remove this view from the DOM. Note that the view isn't present in the
  741. // DOM by default, so calling this method may be a no-op.
  742. remove : function() {
  743. $(this.el).remove();
  744. return this;
  745. },
  746. // For small amounts of DOM Elements, where a full-blown template isn't
  747. // needed, use **make** to manufacture elements, one at a time.
  748. //
  749. // var el = this.make('li', {'class': 'row'}, this.model.escape('title'));
  750. //
  751. make : function(tagName, attributes, content) {
  752. var el = document.createElement(tagName);
  753. if (attributes) $(el).attr(attributes);
  754. if (content) $(el).html(content);
  755. return el;
  756. },
  757. // Set callbacks, where `this.callbacks` is a hash of
  758. //
  759. // *{"event selector": "callback"}*
  760. //
  761. // {
  762. // 'mousedown .title': 'edit',
  763. // 'click .button': 'save'
  764. // }
  765. //
  766. // pairs. Callbacks will be bound to the view, with `this` set properly.
  767. // Uses event delegation for efficiency.
  768. // Omitting the selector binds the event to `this.el`.
  769. // This only works for delegate-able events: not `focus`, `blur`, and
  770. // not `change`, `submit`, and `reset` in Internet Explorer.
  771. delegateEvents : function(events) {
  772. if (!(events || (events = this.events))) return;
  773. $(this.el).unbind('.delegateEvents' + this.cid);
  774. for (var key in events) {
  775. var methodName = events[key];
  776. var match = key.match(eventSplitter);
  777. var eventName = match[1], selector = match[2];
  778. var method = _.bind(this[methodName], this);
  779. eventName += '.delegateEvents' + this.cid;
  780. if (selector === '') {
  781. $(this.el).bind(eventName, method);
  782. } else {
  783. $(this.el).delegate(selector, eventName, method);
  784. }
  785. }
  786. },
  787. // Performs the initial configuration of a View with a set of options.
  788. // Keys with special meaning *(model, collection, id, className)*, are
  789. // attached directly to the view.
  790. _configure : function(options) {
  791. if (this.options) options = _.extend({}, this.options, options);
  792. for (var i = 0, l = viewOptions.length; i < l; i++) {
  793. var attr = viewOptions[i];
  794. if (options[attr]) this[attr] = options[attr];
  795. }
  796. this.options = options;
  797. },
  798. // Ensure that the View has a DOM element to render into.
  799. // If `this.el` is a string, pass it through `$()`, take the first
  800. // matching element, and re-assign it to `el`. Otherwise, create
  801. // an element from the `id`, `className` and `tagName` proeprties.
  802. _ensureElement : function() {
  803. if (!this.el) {
  804. var attrs = this.attributes || {};
  805. if (this.id) attrs.id = this.id;
  806. if (this.className) attrs['class'] = this.className;
  807. this.el = this.make(this.tagName, attrs);
  808. } else if (_.isString(this.el)) {
  809. this.el = $(this.el).get(0);
  810. }
  811. }
  812. });
  813. // The self-propagating extend function that Backbone classes use.
  814. var extend = function (protoProps, classProps) {
  815. var child = inherits(this, protoProps, classProps);
  816. child.extend = extend;
  817. return child;
  818. };
  819. // Set up inheritance for the model, collection, and view.
  820. Backbone.Model.extend = Backbone.Collection.extend =
  821. Backbone.Controller.extend = Backbone.View.extend = extend;
  822. // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
  823. var methodMap = {
  824. 'create': 'POST',
  825. 'update': 'PUT',
  826. 'delete': 'DELETE',
  827. 'read' : 'GET'
  828. };
  829. // Backbone.sync
  830. // -------------
  831. // Override this function to change the manner in which Backbone persists
  832. // models to the server. You will be passed the type of request, and the
  833. // model in question. By default, uses makes a RESTful Ajax request
  834. // to the model's `url()`. Some possible customizations could be:
  835. //
  836. // * Use `setTimeout` to batch rapid-fire updates into a single request.
  837. // * Send up the models as XML instead of JSON.
  838. // * Persist models via WebSockets instead of Ajax.
  839. //
  840. // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
  841. // as `POST`, with a `_method` parameter containing the true HTTP method,
  842. // as well as all requests with the body as `application/x-www-form-urlencoded` instead of
  843. // `application/json` with the model in a param named `model`.
  844. // Useful when interfacing with server-side languages like **PHP** that make
  845. // it difficult to read the body of `PUT` requests.
  846. Backbone.sync = function(method, model, options) {
  847. var type = methodMap[method];
  848. // Default JSON-request options.
  849. var params = _.extend({
  850. type: type,
  851. contentType: 'application/json',
  852. dataType: 'json',
  853. processData: false
  854. }, options);
  855. // Ensure that we have a URL.
  856. if (!params.url) {
  857. params.url = getUrl(model) || urlError();
  858. }
  859. // Ensure that we have the appropriate request data.
  860. if (!params.data && model && (method == 'create' || method == 'update')) {
  861. params.data = JSON.stringify(model.toJSON());
  862. }
  863. // For older servers, emulate JSON by encoding the request into an HTML-form.
  864. if (Backbone.emulateJSON) {
  865. params.contentType = 'application/x-www-form-urlencoded';
  866. params.processData = true;
  867. params.data = params.data ? {model : params.data} : {};
  868. }
  869. // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
  870. // And an `X-HTTP-Method-Override` header.
  871. if (Backbone.emulateHTTP) {
  872. if (type === 'PUT' || type === 'DELETE') {
  873. if (Backbone.emulateJSON) params.data._method = type;
  874. params.type = 'POST';
  875. params.beforeSend = function(xhr) {
  876. xhr.setRequestHeader('X-HTTP-Method-Override', type);
  877. };
  878. }
  879. }
  880. // Make the request.
  881. $.ajax(params);
  882. };
  883. // Helpers
  884. // -------
  885. // Shared empty constructor function to aid in prototype-chain creation.
  886. var ctor = function(){};
  887. // Helper function to correctly set up the prototype chain, for subclasses.
  888. // Similar to `goog.inherits`, but uses a hash of prototype properties and
  889. // class properties to be extended.
  890. var inherits = function(parent, protoProps, staticProps) {
  891. var child;
  892. // The constructor function for the new subclass is either defined by you
  893. // (the "constructor" property in your `extend` definition), or defaulted
  894. // by us to simply call `super()`.
  895. if (protoProps && protoProps.hasOwnProperty('constructor')) {
  896. child = protoProps.constructor;
  897. } else {
  898. child = function(){ return parent.apply(this, arguments); };
  899. }
  900. // Inherit class (static) properties from parent.
  901. _.extend(child, parent);
  902. // Set the prototype chain to inherit from `parent`, without calling
  903. // `parent`'s constructor function.
  904. ctor.prototype = parent.prototype;
  905. child.prototype = new ctor();
  906. // Add prototype properties (instance properties) to the subclass,
  907. // if supplied.
  908. if (protoProps) _.extend(child.prototype, protoProps);
  909. // Add static properties to the constructor function, if supplied.
  910. if (staticProps) _.extend(child, staticProps);
  911. // Correctly set child's `prototype.constructor`, for `instanceof`.
  912. child.prototype.constructor = child;
  913. // Set a convenience property in case the parent's prototype is needed later.
  914. child.__super__ = parent.prototype;
  915. return child;
  916. };
  917. // Helper function to get a URL from a Model or Collection as a property
  918. // or as a function.
  919. var getUrl = function(object) {
  920. if (!(object && object.url)) return null;
  921. return _.isFunction(object.url) ? object.url() : object.url;
  922. };
  923. // Throw an error when a URL is needed, and none is supplied.
  924. var urlError = function() {
  925. throw new Error("A 'url' property or function must be specified");
  926. };
  927. // Wrap an optional error callback with a fallback error event.
  928. var wrapError = function(onError, model, options) {
  929. return function(resp) {
  930. if (onError) {
  931. onError(model, resp, options);
  932. } else {
  933. model.trigger('error', model, resp, options);
  934. }
  935. };
  936. };
  937. // Helper function to escape a string for HTML rendering.
  938. var escapeHTML = function(string) {
  939. return string.replace(/&(?!\w+;|#\d+;|#x[\da-f]+;)/gi, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  940. };
  941. }).call(this);