PageRenderTime 61ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/ext/backbone/0.3.3/backbone.js

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