PageRenderTime 47ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/auiplugin/src/main/resources/experimental/js/external/backbone/backbone.js

https://bitbucket.org/puxlit/aui-archive
JavaScript | 1017 lines | 614 code | 134 blank | 269 comment | 175 complexity | 5a0b34eb125393d57c3136a1074f4c77 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. var index;
  489. if ("index" in options) {
  490. index = options.index;
  491. } else {
  492. index = this.comparator ? this.sortedIndex(model, this.comparator) : this.length;
  493. }
  494. this.models.splice(this.indexOf(model), 1);
  495. this.length--;
  496. if (!options.silent) model.trigger('remove', model, this, options);
  497. model.unbind('all', this._boundOnModelEvent);
  498. return model;
  499. },
  500. // Internal method called every time a model in the set fires an event.
  501. // Sets need to update their indexes when models change ids. All other
  502. // events simply proxy through.
  503. _onModelEvent : function(ev, model) {
  504. if (ev === 'change:id') {
  505. delete this._byId[model.previous('id')];
  506. this._byId[model.id] = model;
  507. }
  508. this.trigger.apply(this, arguments);
  509. }
  510. });
  511. // Underscore methods that we want to implement on the Collection.
  512. var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find', 'detect',
  513. 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include',
  514. 'invoke', 'max', 'min', 'sortBy', 'sortedIndex', 'toArray', 'size',
  515. 'first', 'rest', 'last', 'without', 'indexOf', 'lastIndexOf', 'isEmpty'];
  516. // Mix in each Underscore method as a proxy to `Collection#models`.
  517. _.each(methods, function(method) {
  518. Backbone.Collection.prototype[method] = function() {
  519. return _[method].apply(_, [this.models].concat(_.toArray(arguments)));
  520. };
  521. });
  522. // Backbone.Controller
  523. // -------------------
  524. // Controllers map faux-URLs to actions, and fire events when routes are
  525. // matched. Creating a new one sets its `routes` hash, if not set statically.
  526. Backbone.Controller = function(options) {
  527. options || (options = {});
  528. if (options.routes) this.routes = options.routes;
  529. this._bindRoutes();
  530. this.initialize(options);
  531. };
  532. // Cached regular expressions for matching named param parts and splatted
  533. // parts of route strings.
  534. var namedParam = /:([\w\d]+)/g;
  535. var splatParam = /\*([\w\d]+)/g;
  536. // Set up all inheritable **Backbone.Controller** properties and methods.
  537. _.extend(Backbone.Controller.prototype, Backbone.Events, {
  538. // Initialize is an empty function by default. Override it with your own
  539. // initialization logic.
  540. initialize : function(){},
  541. // Manually bind a single named route to a callback. For example:
  542. //
  543. // this.route('search/:query/p:num', 'search', function(query, num) {
  544. // ...
  545. // });
  546. //
  547. route : function(route, name, callback) {
  548. Backbone.history || (Backbone.history = new Backbone.History);
  549. if (!_.isRegExp(route)) route = this._routeToRegExp(route);
  550. Backbone.history.route(route, _.bind(function(fragment) {
  551. var args = this._extractParameters(route, fragment);
  552. callback.apply(this, args);
  553. this.trigger.apply(this, ['route:' + name].concat(args));
  554. }, this));
  555. },
  556. // Simple proxy to `Backbone.history` to save a fragment into the history,
  557. // without triggering routes.
  558. saveLocation : function(fragment) {
  559. Backbone.history.saveLocation(fragment);
  560. },
  561. // Bind all defined routes to `Backbone.history`.
  562. _bindRoutes : function() {
  563. if (!this.routes) return;
  564. for (var route in this.routes) {
  565. var name = this.routes[route];
  566. this.route(route, name, this[name]);
  567. }
  568. },
  569. // Convert a route string into a regular expression, suitable for matching
  570. // against the current location fragment.
  571. _routeToRegExp : function(route) {
  572. route = route.replace(namedParam, "([^\/]*)").replace(splatParam, "(.*?)");
  573. return new RegExp('^' + route + '$');
  574. },
  575. // Given a route, and a URL fragment that it matches, return the array of
  576. // extracted parameters.
  577. _extractParameters : function(route, fragment) {
  578. return route.exec(fragment).slice(1);
  579. }
  580. });
  581. // Backbone.History
  582. // ----------------
  583. // Handles cross-browser history management, based on URL hashes. If the
  584. // browser does not support `onhashchange`, falls back to polling.
  585. Backbone.History = function() {
  586. this.handlers = [];
  587. this.fragment = this.getFragment();
  588. _.bindAll(this, 'checkUrl');
  589. };
  590. // Cached regex for cleaning hashes.
  591. var hashStrip = /^#*/;
  592. // Set up all inheritable **Backbone.History** properties and methods.
  593. _.extend(Backbone.History.prototype, {
  594. // The default interval to poll for hash changes, if necessary, is
  595. // twenty times a second.
  596. interval: 50,
  597. // Get the cross-browser normalized URL fragment.
  598. getFragment : function(loc) {
  599. return (loc || window.location).hash.replace(hashStrip, '');
  600. },
  601. // Start the hash change handling, returning `true` if the current URL matches
  602. // an existing route, and `false` otherwise.
  603. start : function() {
  604. var docMode = document.documentMode;
  605. var oldIE = ($.browser.msie && (!docMode || docMode <= 7));
  606. if (oldIE) {
  607. this.iframe = $('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
  608. }
  609. if ('onhashchange' in window && !oldIE) {
  610. $(window).bind('hashchange', this.checkUrl);
  611. } else {
  612. setInterval(this.checkUrl, this.interval);
  613. }
  614. return this.loadUrl();
  615. },
  616. // Add a route to be tested when the hash changes. Routes are matched in the
  617. // order they are added.
  618. route : function(route, callback) {
  619. this.handlers.push({route : route, callback : callback});
  620. },
  621. // Checks the current URL to see if it has changed, and if it has,
  622. // calls `loadUrl`, normalizing across the hidden iframe.
  623. checkUrl : function() {
  624. var current = this.getFragment();
  625. if (current == this.fragment && this.iframe) {
  626. current = this.getFragment(this.iframe.location);
  627. }
  628. if (current == this.fragment ||
  629. current == decodeURIComponent(this.fragment)) return false;
  630. if (this.iframe) {
  631. window.location.hash = this.iframe.location.hash = current;
  632. }
  633. this.loadUrl();
  634. },
  635. // Attempt to load the current URL fragment. If a route succeeds with a
  636. // match, returns `true`. If no defined routes matches the fragment,
  637. // returns `false`.
  638. loadUrl : function() {
  639. var fragment = this.fragment = this.getFragment();
  640. var matched = _.any(this.handlers, function(handler) {
  641. if (handler.route.test(fragment)) {
  642. handler.callback(fragment);
  643. return true;
  644. }
  645. });
  646. return matched;
  647. },
  648. // Save a fragment into the hash history. You are responsible for properly
  649. // URL-encoding the fragment in advance. This does not trigger
  650. // a `hashchange` event.
  651. saveLocation : function(fragment) {
  652. fragment = (fragment || '').replace(hashStrip, '');
  653. if (this.fragment == fragment) return;
  654. window.location.hash = this.fragment = fragment;
  655. if (this.iframe && (fragment != this.getFragment(this.iframe.location))) {
  656. this.iframe.document.open().close();
  657. this.iframe.location.hash = fragment;
  658. }
  659. }
  660. });
  661. // Backbone.View
  662. // -------------
  663. // Creating a Backbone.View creates its initial element outside of the DOM,
  664. // if an existing element is not provided...
  665. Backbone.View = function(options) {
  666. this._configure(options || {});
  667. this._ensureElement();
  668. this.delegateEvents();
  669. this.initialize(options);
  670. };
  671. // Element lookup, scoped to DOM elements within the current view.
  672. // This should be prefered to global lookups, if you're dealing with
  673. // a specific view.
  674. var selectorDelegate = function(selector) {
  675. return $(selector, this.el);
  676. };
  677. // Cached regex to split keys for `delegate`.
  678. var eventSplitter = /^(\w+)\s*(.*)$/;
  679. // Set up all inheritable **Backbone.View** properties and methods.
  680. _.extend(Backbone.View.prototype, Backbone.Events, {
  681. // The default `tagName` of a View's element is `"div"`.
  682. tagName : 'div',
  683. // Attach the `selectorDelegate` function as the `$` property.
  684. $ : selectorDelegate,
  685. // Initialize is an empty function by default. Override it with your own
  686. // initialization logic.
  687. initialize : function(){},
  688. // **render** is the core function that your view should override, in order
  689. // to populate its element (`this.el`), with the appropriate HTML. The
  690. // convention is for **render** to always return `this`.
  691. render : function() {
  692. return this;
  693. },
  694. // Remove this view from the DOM. Note that the view isn't present in the
  695. // DOM by default, so calling this method may be a no-op.
  696. remove : function() {
  697. $(this.el).remove();
  698. return this;
  699. },
  700. // For small amounts of DOM Elements, where a full-blown template isn't
  701. // needed, use **make** to manufacture elements, one at a time.
  702. //
  703. // var el = this.make('li', {'class': 'row'}, this.model.escape('title'));
  704. //
  705. make : function(tagName, attributes, content) {
  706. var el = document.createElement(tagName);
  707. if (attributes) $(el).attr(attributes);
  708. if (content) $(el).html(content);
  709. return el;
  710. },
  711. // Set callbacks, where `this.callbacks` is a hash of
  712. //
  713. // *{"event selector": "callback"}*
  714. //
  715. // {
  716. // 'mousedown .title': 'edit',
  717. // 'click .button': 'save'
  718. // }
  719. //
  720. // pairs. Callbacks will be bound to the view, with `this` set properly.
  721. // Uses event delegation for efficiency.
  722. // Omitting the selector binds the event to `this.el`.
  723. // This only works for delegate-able events: not `focus`, `blur`, and
  724. // not `change`, `submit`, and `reset` in Internet Explorer.
  725. delegateEvents : function(events) {
  726. if (!(events || (events = this.events))) return;
  727. $(this.el).unbind();
  728. for (var key in events) {
  729. var methodName = events[key];
  730. var match = key.match(eventSplitter);
  731. var eventName = match[1], selector = match[2];
  732. var method = _.bind(this[methodName], this);
  733. if (selector === '') {
  734. $(this.el).bind(eventName, method);
  735. } else {
  736. $(this.el).delegate(selector, eventName, method);
  737. }
  738. }
  739. },
  740. // Performs the initial configuration of a View with a set of options.
  741. // Keys with special meaning *(model, collection, id, className)*, are
  742. // attached directly to the view.
  743. _configure : function(options) {
  744. if (this.options) options = _.extend({}, this.options, options);
  745. if (options.model) this.model = options.model;
  746. if (options.collection) this.collection = options.collection;
  747. if (options.el) this.el = options.el;
  748. if (options.id) this.id = options.id;
  749. if (options.className) this.className = options.className;
  750. if (options.tagName) this.tagName = options.tagName;
  751. this.options = options;
  752. },
  753. // Ensure that the View has a DOM element to render into.
  754. _ensureElement : function() {
  755. if (this.el) return;
  756. var attrs = {};
  757. if (this.id) attrs.id = this.id;
  758. if (this.className) attrs["class"] = this.className;
  759. this.el = this.make(this.tagName, attrs);
  760. }
  761. });
  762. // The self-propagating extend function that Backbone classes use.
  763. var extend = function (protoProps, classProps) {
  764. var child = inherits(this, protoProps, classProps);
  765. child.extend = extend;
  766. return child;
  767. };
  768. // Set up inheritance for the model, collection, and view.
  769. Backbone.Model.extend = Backbone.Collection.extend =
  770. Backbone.Controller.extend = Backbone.View.extend = extend;
  771. // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
  772. var methodMap = {
  773. 'create': 'POST',
  774. 'update': 'PUT',
  775. 'delete': 'DELETE',
  776. 'read' : 'GET'
  777. };
  778. // Backbone.sync
  779. // -------------
  780. // Override this function to change the manner in which Backbone persists
  781. // models to the server. You will be passed the type of request, and the
  782. // model in question. By default, uses makes a RESTful Ajax request
  783. // to the model's `url()`. Some possible customizations could be:
  784. //
  785. // * Use `setTimeout` to batch rapid-fire updates into a single request.
  786. // * Send up the models as XML instead of JSON.
  787. // * Persist models via WebSockets instead of Ajax.
  788. //
  789. // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
  790. // as `POST`, with a `_method` parameter containing the true HTTP method,
  791. // as well as all requests with the body as `application/x-www-form-urlencoded` instead of
  792. // `application/json` with the model in a param named `model`.
  793. // Useful when interfacing with server-side languages like **PHP** that make
  794. // it difficult to read the body of `PUT` requests.
  795. Backbone.sync = function(method, model, success, error) {
  796. var type = methodMap[method];
  797. var modelJSON = (method === 'create' || method === 'update') ?
  798. JSON.stringify(model.toJSON()) : null;
  799. // Default JSON-request options.
  800. var params = {
  801. url: getUrl(model),
  802. type: type,
  803. contentType: 'application/json',
  804. data: modelJSON,
  805. dataType: 'json',
  806. processData: false,
  807. success: success,
  808. error: error
  809. };
  810. // For older servers, emulate JSON by encoding the request into an HTML-form.
  811. if (Backbone.emulateJSON) {
  812. params.contentType = 'application/x-www-form-urlencoded';
  813. params.processData = true;
  814. params.data = modelJSON ? {model : modelJSON} : {};
  815. }
  816. // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
  817. // And an `X-HTTP-Method-Override` header.
  818. if (Backbone.emulateHTTP) {
  819. if (type === 'PUT' || type === 'DELETE') {
  820. if (Backbone.emulateJSON) params.data._method = type;
  821. params.type = 'POST';
  822. params.beforeSend = function(xhr) {
  823. xhr.setRequestHeader("X-HTTP-Method-Override", type);
  824. };
  825. }
  826. }
  827. // Make the request.
  828. $.ajax(params);
  829. };
  830. // Helpers
  831. // -------
  832. // Shared empty constructor function to aid in prototype-chain creation.
  833. var ctor = function(){};
  834. // Helper function to correctly set up the prototype chain, for subclasses.
  835. // Similar to `goog.inherits`, but uses a hash of prototype properties and
  836. // class properties to be extended.
  837. var inherits = function(parent, protoProps, staticProps) {
  838. var child;
  839. // The constructor function for the new subclass is either defined by you
  840. // (the "constructor" property in your `extend` definition), or defaulted
  841. // by us to simply call `super()`.
  842. if (protoProps && protoProps.hasOwnProperty('constructor')) {
  843. child = protoProps.constructor;
  844. } else {
  845. child = function(){ return parent.apply(this, arguments); };
  846. }
  847. // Set the prototype chain to inherit from `parent`, without calling
  848. // `parent`'s constructor function.
  849. ctor.prototype = parent.prototype;
  850. child.prototype = new ctor();
  851. // Add prototype properties (instance properties) to the subclass,
  852. // if supplied.
  853. if (protoProps) _.extend(child.prototype, protoProps);
  854. // Add static properties to the constructor function, if supplied.
  855. if (staticProps) _.extend(child, staticProps);
  856. // Correctly set child's `prototype.constructor`, for `instanceof`.
  857. child.prototype.constructor = child;
  858. // Set a convenience property in case the parent's prototype is needed later.
  859. child.__super__ = parent.prototype;
  860. return child;
  861. };
  862. // Helper function to get a URL from a Model or Collection as a property
  863. // or as a function.
  864. var getUrl = function(object) {
  865. if (!(object && object.url)) throw new Error("A 'url' property or function must be specified");
  866. return _.isFunction(object.url) ? object.url() : object.url;
  867. };
  868. // Wrap an optional error callback with a fallback error event.
  869. var wrapError = function(onError, model, options) {
  870. return function(resp) {
  871. if (onError) {
  872. onError(model, resp);
  873. } else {
  874. model.trigger('error', model, resp, options);
  875. }
  876. };
  877. };
  878. // Helper function to escape a string for HTML rendering.
  879. var escapeHTML = function(string) {
  880. return string.replace(/&(?!\w+;)/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  881. };
  882. })();