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

/backbone.js

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