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

/vendor/assets/javascripts/backbone.js

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