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

/website/static/js/backbone.js

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