backbone.js 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508
  1. // Backbone.js 0.9.10
  2. // (c) 2010-2013 Jeremy Ashkenas, DocumentCloud Inc.
  3. // Backbone may be freely distributed under the MIT license.
  4. // For all details and documentation:
  5. // http://backbonejs.org
  6. (function(){
  7. // Initial Setup
  8. // -------------
  9. // Save a reference to the global object (`window` in the browser, `exports`
  10. // on the server).
  11. var root = this;
  12. // Save the previous value of the `Backbone` variable, so that it can be
  13. // restored later on, if `noConflict` is used.
  14. var previousBackbone = root.Backbone;
  15. // Create a local reference to array methods.
  16. var array = [];
  17. var push = array.push;
  18. var slice = array.slice;
  19. var splice = array.splice;
  20. // The top-level namespace. All public Backbone classes and modules will
  21. // be attached to this. Exported for both CommonJS and the browser.
  22. var Backbone;
  23. if (typeof exports !== 'undefined') {
  24. Backbone = exports;
  25. } else {
  26. Backbone = root.Backbone = {};
  27. }
  28. // Current version of the library. Keep in sync with `package.json`.
  29. Backbone.VERSION = '0.9.10';
  30. // Require Underscore, if we're on the server, and it's not already present.
  31. var _ = root._;
  32. if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
  33. // For Backbone's purposes, jQuery, Zepto, or Ender owns the `$` variable.
  34. Backbone.$ = root.jQuery || root.Zepto || root.ender;
  35. // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
  36. // to its previous owner. Returns a reference to this Backbone object.
  37. Backbone.noConflict = function() {
  38. root.Backbone = previousBackbone;
  39. return this;
  40. };
  41. // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
  42. // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and
  43. // set a `X-Http-Method-Override` header.
  44. Backbone.emulateHTTP = false;
  45. // Turn on `emulateJSON` to support legacy servers that can't deal with direct
  46. // `application/json` requests ... will encode the body as
  47. // `application/x-www-form-urlencoded` instead and will send the model in a
  48. // form param named `model`.
  49. Backbone.emulateJSON = false;
  50. // Backbone.Events
  51. // ---------------
  52. // Regular expression used to split event strings.
  53. var eventSplitter = /\s+/;
  54. // Implement fancy features of the Events API such as multiple event
  55. // names `"change blur"` and jQuery-style event maps `{change: action}`
  56. // in terms of the existing API.
  57. var eventsApi = function(obj, action, name, rest) {
  58. if (!name) return true;
  59. // Handle event maps.
  60. if (typeof name === 'object') {
  61. for (var key in name) {
  62. obj[action].apply(obj, [key, name[key]].concat(rest));
  63. }
  64. return false;
  65. }
  66. // Handle space separated event names.
  67. if (eventSplitter.test(name)) {
  68. var names = name.split(eventSplitter);
  69. for (var i = 0, l = names.length; i < l; i++) {
  70. obj[action].apply(obj, [names[i]].concat(rest));
  71. }
  72. return false;
  73. }
  74. return true;
  75. };
  76. // Optimized internal dispatch function for triggering events. Tries to
  77. // keep the usual cases speedy (most Backbone events have 3 arguments).
  78. var triggerEvents = function(events, args) {
  79. var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
  80. switch (args.length) {
  81. case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx);
  82. return;
  83. case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1);
  84. return;
  85. case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2);
  86. return;
  87. case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3);
  88. return;
  89. default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
  90. }
  91. };
  92. // A module that can be mixed in to *any object* in order to provide it with
  93. // custom events. You may bind with `on` or remove with `off` callback
  94. // functions to an event; `trigger`-ing an event fires all callbacks in
  95. // succession.
  96. //
  97. // var object = {};
  98. // _.extend(object, Backbone.Events);
  99. // object.on('expand', function(){ alert('expanded'); });
  100. // object.trigger('expand');
  101. //
  102. var Events = Backbone.Events = {
  103. // Bind one or more space separated events, or an events map,
  104. // to a `callback` function. Passing `"all"` will bind the callback to
  105. // all events fired.
  106. on: function(name, callback, context) {
  107. if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
  108. this._events || (this._events = {});
  109. var events = this._events[name] || (this._events[name] = []);
  110. events.push({callback: callback, context: context, ctx: context || this});
  111. return this;
  112. },
  113. // Bind events to only be triggered a single time. After the first time
  114. // the callback is invoked, it will be removed.
  115. once: function(name, callback, context) {
  116. if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this;
  117. var self = this;
  118. var once = _.once(function() {
  119. self.off(name, once);
  120. callback.apply(this, arguments);
  121. });
  122. once._callback = callback;
  123. return this.on(name, once, context);
  124. },
  125. // Remove one or many callbacks. If `context` is null, removes all
  126. // callbacks with that function. If `callback` is null, removes all
  127. // callbacks for the event. If `name` is null, removes all bound
  128. // callbacks for all events.
  129. off: function(name, callback, context) {
  130. var retain, ev, events, names, i, l, j, k;
  131. if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
  132. if (!name && !callback && !context) {
  133. this._events = {};
  134. return this;
  135. }
  136. names = name ? [name] : _.keys(this._events);
  137. for (i = 0, l = names.length; i < l; i++) {
  138. name = names[i];
  139. if (events = this._events[name]) {
  140. this._events[name] = retain = [];
  141. if (callback || context) {
  142. for (j = 0, k = events.length; j < k; j++) {
  143. ev = events[j];
  144. if ((callback && callback !== ev.callback &&
  145. callback !== ev.callback._callback) ||
  146. (context && context !== ev.context)) {
  147. retain.push(ev);
  148. }
  149. }
  150. }
  151. if (!retain.length) delete this._events[name];
  152. }
  153. }
  154. return this;
  155. },
  156. // Trigger one or many events, firing all bound callbacks. Callbacks are
  157. // passed the same arguments as `trigger` is, apart from the event name
  158. // (unless you're listening on `"all"`, which will cause your callback to
  159. // receive the true name of the event as the first argument).
  160. trigger: function(name) {
  161. if (!this._events) return this;
  162. var args = slice.call(arguments, 1);
  163. if (!eventsApi(this, 'trigger', name, args)) return this;
  164. var events = this._events[name];
  165. var allEvents = this._events.all;
  166. if (events) triggerEvents(events, args);
  167. if (allEvents) triggerEvents(allEvents, arguments);
  168. return this;
  169. },
  170. // Tell this object to stop listening to either specific events ... or
  171. // to every object it's currently listening to.
  172. stopListening: function(obj, name, callback) {
  173. var listeners = this._listeners;
  174. if (!listeners) return this;
  175. var deleteListener = !name && !callback;
  176. if (typeof name === 'object') callback = this;
  177. if (obj) (listeners = {})[obj._listenerId] = obj;
  178. for (var id in listeners) {
  179. listeners[id].off(name, callback, this);
  180. if (deleteListener) delete this._listeners[id];
  181. }
  182. return this;
  183. }
  184. };
  185. var listenMethods = {listenTo: 'on', listenToOnce: 'once'};
  186. // An inversion-of-control versions of `on` and `once`. Tell *this* object to listen to
  187. // an event in another object ... keeping track of what it's listening to.
  188. _.each(listenMethods, function(implementation, method) {
  189. Events[method] = function(obj, name, callback) {
  190. var listeners = this._listeners || (this._listeners = {});
  191. var id = obj._listenerId || (obj._listenerId = _.uniqueId('l'));
  192. listeners[id] = obj;
  193. if (typeof name === 'object') callback = this;
  194. obj[implementation](name, callback, this);
  195. return this;
  196. };
  197. });
  198. // Aliases for backwards compatibility.
  199. Events.bind = Events.on;
  200. Events.unbind = Events.off;
  201. // Allow the `Backbone` object to serve as a global event bus, for folks who
  202. // want global "pubsub" in a convenient place.
  203. _.extend(Backbone, Events);
  204. // Backbone.Model
  205. // --------------
  206. // Create a new model, with defined attributes. A client id (`cid`)
  207. // is automatically generated and assigned for you.
  208. var Model = Backbone.Model = function(attributes, options) {
  209. var defaults;
  210. var attrs = attributes || {};
  211. this.cid = _.uniqueId('c');
  212. this.attributes = {};
  213. if (options && options.collection) this.collection = options.collection;
  214. if (options && options.parse) attrs = this.parse(attrs, options) || {};
  215. if (defaults = _.result(this, 'defaults')) {
  216. attrs = _.defaults({}, attrs, defaults);
  217. }
  218. this.set(attrs, options);
  219. this.changed = {};
  220. this.initialize.apply(this, arguments);
  221. };
  222. // Attach all inheritable methods to the Model prototype.
  223. _.extend(Model.prototype, Events, {
  224. // A hash of attributes whose current and previous value differ.
  225. changed: null,
  226. // The value returned during the last failed validation.
  227. validationError: null,
  228. // The default name for the JSON `id` attribute is `"id"`. MongoDB and
  229. // CouchDB users may want to set this to `"_id"`.
  230. idAttribute: 'id',
  231. // Initialize is an empty function by default. Override it with your own
  232. // initialization logic.
  233. initialize: function(){},
  234. // Return a copy of the model's `attributes` object.
  235. toJSON: function(options) {
  236. return _.clone(this.attributes);
  237. },
  238. // Proxy `Backbone.sync` by default.
  239. sync: function() {
  240. return Backbone.sync.apply(this, arguments);
  241. },
  242. // Get the value of an attribute.
  243. get: function(attr) {
  244. return this.attributes[attr];
  245. },
  246. // Get the HTML-escaped value of an attribute.
  247. escape: function(attr) {
  248. return _.escape(this.get(attr));
  249. },
  250. // Returns `true` if the attribute contains a value that is not null
  251. // or undefined.
  252. has: function(attr) {
  253. return this.get(attr) != null;
  254. },
  255. // ----------------------------------------------------------------------
  256. // Set a hash of model attributes on the object, firing `"change"` unless
  257. // you choose to silence it.
  258. set: function(key, val, options) {
  259. var attr, attrs, unset, changes, silent, changing, prev, current;
  260. if (key == null) return this;
  261. // Handle both `"key", value` and `{key: value}` -style arguments.
  262. if (typeof key === 'object') {
  263. attrs = key;
  264. options = val;
  265. } else {
  266. (attrs = {})[key] = val;
  267. }
  268. options || (options = {});
  269. // Run validation.
  270. if (!this._validate(attrs, options)) return false;
  271. // Extract attributes and options.
  272. unset = options.unset;
  273. silent = options.silent;
  274. changes = [];
  275. changing = this._changing;
  276. this._changing = true;
  277. if (!changing) {
  278. this._previousAttributes = _.clone(this.attributes);
  279. this.changed = {};
  280. }
  281. current = this.attributes, prev = this._previousAttributes;
  282. // Check for changes of `id`.
  283. if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
  284. // For each `set` attribute, update or delete the current value.
  285. for (attr in attrs) {
  286. val = attrs[attr];
  287. if (!_.isEqual(current[attr], val)) changes.push(attr);
  288. if (!_.isEqual(prev[attr], val)) {
  289. this.changed[attr] = val;
  290. } else {
  291. delete this.changed[attr];
  292. }
  293. unset ? delete current[attr] : current[attr] = val;
  294. }
  295. // Trigger all relevant attribute changes.
  296. if (!silent) {
  297. if (changes.length) this._pending = true;
  298. for (var i = 0, l = changes.length; i < l; i++) {
  299. this.trigger('change:' + changes[i], this, current[changes[i]], options);
  300. }
  301. }
  302. if (changing) return this;
  303. if (!silent) {
  304. while (this._pending) {
  305. this._pending = false;
  306. this.trigger('change', this, options);
  307. }
  308. }
  309. this._pending = false;
  310. this._changing = false;
  311. return this;
  312. },
  313. // Remove an attribute from the model, firing `"change"` unless you choose
  314. // to silence it. `unset` is a noop if the attribute doesn't exist.
  315. unset: function(attr, options) {
  316. return this.set(attr, void 0, _.extend({}, options, {unset: true}));
  317. },
  318. // Clear all attributes on the model, firing `"change"` unless you choose
  319. // to silence it.
  320. clear: function(options) {
  321. var attrs = {};
  322. for (var key in this.attributes) attrs[key] = void 0;
  323. return this.set(attrs, _.extend({}, options, {unset: true}));
  324. },
  325. // Determine if the model has changed since the last `"change"` event.
  326. // If you specify an attribute name, determine if that attribute has changed.
  327. hasChanged: function(attr) {
  328. if (attr == null) return !_.isEmpty(this.changed);
  329. return _.has(this.changed, attr);
  330. },
  331. // Return an object containing all the attributes that have changed, or
  332. // false if there are no changed attributes. Useful for determining what
  333. // parts of a view need to be updated and/or what attributes need to be
  334. // persisted to the server. Unset attributes will be set to undefined.
  335. // You can also pass an attributes object to diff against the model,
  336. // determining if there *would be* a change.
  337. changedAttributes: function(diff) {
  338. if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
  339. var val, changed = false;
  340. var old = this._changing ? this._previousAttributes : this.attributes;
  341. for (var attr in diff) {
  342. if (_.isEqual(old[attr], (val = diff[attr]))) continue;
  343. (changed || (changed = {}))[attr] = val;
  344. }
  345. return changed;
  346. },
  347. // Get the previous value of an attribute, recorded at the time the last
  348. // `"change"` event was fired.
  349. previous: function(attr) {
  350. if (attr == null || !this._previousAttributes) return null;
  351. return this._previousAttributes[attr];
  352. },
  353. // Get all of the attributes of the model at the time of the previous
  354. // `"change"` event.
  355. previousAttributes: function() {
  356. return _.clone(this._previousAttributes);
  357. },
  358. // ---------------------------------------------------------------------
  359. // Fetch the model from the server. If the server's representation of the
  360. // model differs from its current attributes, they will be overriden,
  361. // triggering a `"change"` event.
  362. fetch: function(options) {
  363. options = options ? _.clone(options) : {};
  364. if (options.parse === void 0) options.parse = true;
  365. var model = this;
  366. var success = options.success;
  367. options.success = function(resp) {
  368. if (!model.set(model.parse(resp, options), options)) return false;
  369. if (success) success(model, resp, options);
  370. model.trigger('sync', model, resp, options);
  371. };
  372. wrapError(this, options);
  373. return this.sync('read', this, options);
  374. },
  375. // Set a hash of model attributes, and sync the model to the server.
  376. // If the server returns an attributes hash that differs, the model's
  377. // state will be `set` again.
  378. save: function(key, val, options) {
  379. var attrs, method, xhr, attributes = this.attributes;
  380. // Handle both `"key", value` and `{key: value}` -style arguments.
  381. if (key == null || typeof key === 'object') {
  382. attrs = key;
  383. options = val;
  384. } else {
  385. (attrs = {})[key] = val;
  386. }
  387. // If we're not waiting and attributes exist, save acts as `set(attr).save(null, opts)`.
  388. if (attrs && (!options || !options.wait) && !this.set(attrs, options)) return false;
  389. options = _.extend({validate: true}, options);
  390. // Do not persist invalid models.
  391. if (!this._validate(attrs, options)) return false;
  392. // Set temporary attributes if `{wait: true}`.
  393. if (attrs && options.wait) {
  394. this.attributes = _.extend({}, attributes, attrs);
  395. }
  396. // After a successful server-side save, the client is (optionally)
  397. // updated with the server-side state.
  398. if (options.parse === void 0) options.parse = true;
  399. var model = this;
  400. var success = options.success;
  401. options.success = function(resp) {
  402. // Ensure attributes are restored during synchronous saves.
  403. model.attributes = attributes;
  404. var serverAttrs = model.parse(resp, options);
  405. if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
  406. if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
  407. return false;
  408. }
  409. if (success) success(model, resp, options);
  410. model.trigger('sync', model, resp, options);
  411. };
  412. wrapError(this, options);
  413. method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
  414. if (method === 'patch') options.attrs = attrs;
  415. xhr = this.sync(method, this, options);
  416. // Restore attributes.
  417. if (attrs && options.wait) this.attributes = attributes;
  418. return xhr;
  419. },
  420. // Destroy this model on the server if it was already persisted.
  421. // Optimistically removes the model from its collection, if it has one.
  422. // If `wait: true` is passed, waits for the server to respond before removal.
  423. destroy: function(options) {
  424. options = options ? _.clone(options) : {};
  425. var model = this;
  426. var success = options.success;
  427. var destroy = function() {
  428. model.trigger('destroy', model, model.collection, options);
  429. };
  430. options.success = function(resp) {
  431. if (options.wait || model.isNew()) destroy();
  432. if (success) success(model, resp, options);
  433. if (!model.isNew()) model.trigger('sync', model, resp, options);
  434. };
  435. if (this.isNew()) {
  436. options.success();
  437. return false;
  438. }
  439. wrapError(this, options);
  440. var xhr = this.sync('delete', this, options);
  441. if (!options.wait) destroy();
  442. return xhr;
  443. },
  444. // Default URL for the model's representation on the server -- if you're
  445. // using Backbone's restful methods, override this to change the endpoint
  446. // that will be called.
  447. url: function() {
  448. var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError();
  449. if (this.isNew()) return base;
  450. return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id);
  451. },
  452. // **parse** converts a response into the hash of attributes to be `set` on
  453. // the model. The default implementation is just to pass the response along.
  454. parse: function(resp, options) {
  455. return resp;
  456. },
  457. // Create a new model with identical attributes to this one.
  458. clone: function() {
  459. return new this.constructor(this.attributes);
  460. },
  461. // A model is new if it has never been saved to the server, and lacks an id.
  462. isNew: function() {
  463. return this.id == null;
  464. },
  465. // Check if the model is currently in a valid state.
  466. isValid: function(options) {
  467. return !this.validate || !this.validate(this.attributes, options);
  468. },
  469. // Run validation against the next complete set of model attributes,
  470. // returning `true` if all is well. Otherwise, fire an
  471. // `"invalid"` event and call the invalid callback, if specified.
  472. _validate: function(attrs, options) {
  473. if (!options.validate || !this.validate) return true;
  474. attrs = _.extend({}, this.attributes, attrs);
  475. var error = this.validationError = this.validate(attrs, options) || null;
  476. if (!error) return true;
  477. this.trigger('invalid', this, error, options || {});
  478. return false;
  479. }
  480. });
  481. // Backbone.Collection
  482. // -------------------
  483. // Provides a standard collection class for our sets of models, ordered
  484. // or unordered. If a `comparator` is specified, the Collection will maintain
  485. // its models in sort order, as they're added and removed.
  486. var Collection = Backbone.Collection = function(models, options) {
  487. options || (options = {});
  488. if (options.model) this.model = options.model;
  489. if (options.comparator !== void 0) this.comparator = options.comparator;
  490. this._reset();
  491. this.initialize.apply(this, arguments);
  492. if (models) this.reset(models, _.extend({silent: true}, options));
  493. };
  494. // Define the Collection's inheritable methods.
  495. _.extend(Collection.prototype, Events, {
  496. // The default model for a collection is just a **Backbone.Model**.
  497. // This should be overridden in most cases.
  498. model: Model,
  499. // Initialize is an empty function by default. Override it with your own
  500. // initialization logic.
  501. initialize: function(){},
  502. // The JSON representation of a Collection is an array of the
  503. // models' attributes.
  504. toJSON: function(options) {
  505. return this.map(function(model){ return model.toJSON(options); });
  506. },
  507. // Proxy `Backbone.sync` by default.
  508. sync: function() {
  509. return Backbone.sync.apply(this, arguments);
  510. },
  511. // Add a model, or list of models to the set.
  512. add: function(models, options) {
  513. models = _.isArray(models) ? models.slice() : [models];
  514. options || (options = {});
  515. var i, l, model, attrs, existing, doSort, add, at, sort, sortAttr;
  516. add = [];
  517. at = options.at;
  518. sort = this.comparator && (at == null) && options.sort !== false;
  519. sortAttr = _.isString(this.comparator) ? this.comparator : null;
  520. var modelMap = {};
  521. // Turn bare objects into model references, and prevent invalid models
  522. // from being added.
  523. for (i = 0, l = models.length; i < l; i++) {
  524. if (!(model = this._prepareModel(attrs = models[i], options))) continue;
  525. // If a duplicate is found, prevent it from being added and
  526. // optionally merge it into the existing model.
  527. if (existing = this.get(model)) {
  528. modelMap[existing.cid] = true;
  529. if (options.merge) {
  530. existing.set(attrs === model ? model.attributes : attrs, options);
  531. if (sort && !doSort && existing.hasChanged(sortAttr)) doSort = true;
  532. }
  533. continue;
  534. }
  535. if (options.add === false) continue;
  536. // This is a new model, push it to the `add` list.
  537. add.push(model);
  538. // Listen to added models' events, and index models for lookup by
  539. // `id` and by `cid`.
  540. model.on('all', this._onModelEvent, this);
  541. this._byId[model.cid] = model;
  542. if (model.id != null) this._byId[model.id] = model;
  543. }
  544. if (options.remove) {
  545. var remove = [];
  546. for (i = 0, l = this.length; i < l; ++i) {
  547. if (!modelMap[(model = this.models[i]).cid]) remove.push(model);
  548. }
  549. if (remove.length) this.remove(remove, options);
  550. }
  551. // See if sorting is needed, update `length` and splice in new models.
  552. if (add.length) {
  553. if (sort) doSort = true;
  554. this.length += add.length;
  555. if (at != null) {
  556. splice.apply(this.models, [at, 0].concat(add));
  557. } else {
  558. push.apply(this.models, add);
  559. }
  560. }
  561. // Silently sort the collection if appropriate.
  562. if (doSort) this.sort({silent: true});
  563. if (options.silent) return this;
  564. // Trigger `add` events.
  565. for (i = 0, l = add.length; i < l; i++) {
  566. (model = add[i]).trigger('add', model, this, options);
  567. }
  568. // Trigger `sort` if the collection was sorted.
  569. if (doSort) this.trigger('sort', this, options);
  570. return this;
  571. },
  572. // Remove a model, or a list of models from the set.
  573. remove: function(models, options) {
  574. models = _.isArray(models) ? models.slice() : [models];
  575. options || (options = {});
  576. var i, l, index, model;
  577. for (i = 0, l = models.length; i < l; i++) {
  578. model = this.get(models[i]);
  579. if (!model) continue;
  580. delete this._byId[model.id];
  581. delete this._byId[model.cid];
  582. index = this.indexOf(model);
  583. this.models.splice(index, 1);
  584. this.length--;
  585. if (!options.silent) {
  586. options.index = index;
  587. model.trigger('remove', model, this, options);
  588. }
  589. this._removeReference(model);
  590. }
  591. return this;
  592. },
  593. // Add a model to the end of the collection.
  594. push: function(model, options) {
  595. model = this._prepareModel(model, options);
  596. this.add(model, _.extend({at: this.length}, options));
  597. return model;
  598. },
  599. // Remove a model from the end of the collection.
  600. pop: function(options) {
  601. var model = this.at(this.length - 1);
  602. this.remove(model, options);
  603. return model;
  604. },
  605. // Add a model to the beginning of the collection.
  606. unshift: function(model, options) {
  607. model = this._prepareModel(model, options);
  608. this.add(model, _.extend({at: 0}, options));
  609. return model;
  610. },
  611. // Remove a model from the beginning of the collection.
  612. shift: function(options) {
  613. var model = this.at(0);
  614. this.remove(model, options);
  615. return model;
  616. },
  617. // Slice out a sub-array of models from the collection.
  618. slice: function(begin, end) {
  619. return this.models.slice(begin, end);
  620. },
  621. // Get a model from the set by id.
  622. get: function(obj) {
  623. if (obj == null) return void 0;
  624. return this._byId[obj.id != null ? obj.id : obj.cid || obj];
  625. },
  626. // Get the model at the given index.
  627. at: function(index) {
  628. return this.models[index];
  629. },
  630. // Return models with matching attributes. Useful for simple cases of
  631. // `filter`.
  632. where: function(attrs, first) {
  633. if (_.isEmpty(attrs)) return first ? void 0 : [];
  634. return this[first ? 'find' : 'filter'](function(model) {
  635. for (var key in attrs) {
  636. if (attrs[key] !== model.get(key)) return false;
  637. }
  638. return true;
  639. });
  640. },
  641. // Return the first model with matching attributes. Useful for simple cases
  642. // of `find`.
  643. findWhere: function(attrs) {
  644. return this.where(attrs, true);
  645. },
  646. // Force the collection to re-sort itself. You don't need to call this under
  647. // normal circumstances, as the set will maintain sort order as each item
  648. // is added.
  649. sort: function(options) {
  650. if (!this.comparator) {
  651. throw new Error('Cannot sort a set without a comparator');
  652. }
  653. options || (options = {});
  654. // Run sort based on type of `comparator`.
  655. if (_.isString(this.comparator) || this.comparator.length === 1) {
  656. this.models = this.sortBy(this.comparator, this);
  657. } else {
  658. this.models.sort(_.bind(this.comparator, this));
  659. }
  660. if (!options.silent) this.trigger('sort', this, options);
  661. return this;
  662. },
  663. // Pluck an attribute from each model in the collection.
  664. pluck: function(attr) {
  665. return _.invoke(this.models, 'get', attr);
  666. },
  667. // Smartly update a collection with a change set of models, adding,
  668. // removing, and merging as necessary.
  669. update: function(models, options) {
  670. options = _.extend({merge: true, remove: true}, options);
  671. if (options.parse) models = this.parse(models, options);
  672. this.add(models, options);
  673. return this;
  674. },
  675. // When you have more items than you want to add or remove individually,
  676. // you can reset the entire set with a new list of models, without firing
  677. // any `add` or `remove` events. Fires `reset` when finished.
  678. reset: function(models, options) {
  679. options = options ? _.clone(options) : {};
  680. if (options.parse) models = this.parse(models, options);
  681. for (var i = 0, l = this.models.length; i < l; i++) {
  682. this._removeReference(this.models[i]);
  683. }
  684. options.previousModels = this.models;
  685. this._reset();
  686. if (models) this.add(models, _.extend({silent: true}, options));
  687. if (!options.silent) this.trigger('reset', this, options);
  688. return this;
  689. },
  690. // Fetch the default set of models for this collection, resetting the
  691. // collection when they arrive. If `update: true` is passed, the response
  692. // data will be passed through the `update` method instead of `reset`.
  693. fetch: function(options) {
  694. options = options ? _.clone(options) : {};
  695. if (options.parse === void 0) options.parse = true;
  696. var success = options.success;
  697. var collection = this;
  698. options.success = function(resp) {
  699. var method = options.update ? 'update' : 'reset';
  700. collection[method](resp, options);
  701. if (success) success(collection, resp, options);
  702. collection.trigger('sync', collection, resp, options);
  703. };
  704. wrapError(this, options);
  705. return this.sync('read', this, options);
  706. },
  707. // Create a new instance of a model in this collection. Add the model to the
  708. // collection immediately, unless `wait: true` is passed, in which case we
  709. // wait for the server to agree.
  710. create: function(model, options) {
  711. options = options ? _.clone(options) : {};
  712. if (!(model = this._prepareModel(model, options))) return false;
  713. if (!options.wait) this.add(model, options);
  714. var collection = this;
  715. var success = options.success;
  716. options.success = function(resp) {
  717. if (options.wait) collection.add(model, options);
  718. if (success) success(model, resp, options);
  719. };
  720. model.save(null, options);
  721. return model;
  722. },
  723. // **parse** converts a response into a list of models to be added to the
  724. // collection. The default implementation is just to pass it through.
  725. parse: function(resp, options) {
  726. return resp;
  727. },
  728. // Create a new collection with an identical list of models as this one.
  729. clone: function() {
  730. return new this.constructor(this.models);
  731. },
  732. // Reset all internal state. Called when the collection is reset.
  733. _reset: function() {
  734. this.length = 0;
  735. this.models = [];
  736. this._byId = {};
  737. },
  738. // Prepare a model or hash of attributes to be added to this collection.
  739. _prepareModel: function(attrs, options) {
  740. if (attrs instanceof Model) {
  741. if (!attrs.collection) attrs.collection = this;
  742. return attrs;
  743. }
  744. options || (options = {});
  745. options.collection = this;
  746. var model = new this.model(attrs, options);
  747. if (!model._validate(attrs, options)) {
  748. this.trigger('invalid', this, attrs, options);
  749. return false;
  750. }
  751. return model;
  752. },
  753. // Internal method to remove a model's ties to a collection.
  754. _removeReference: function(model) {
  755. if (this === model.collection) delete model.collection;
  756. model.off('all', this._onModelEvent, this);
  757. },
  758. // Internal method called every time a model in the set fires an event.
  759. // Sets need to update their indexes when models change ids. All other
  760. // events simply proxy through. "add" and "remove" events that originate
  761. // in other collections are ignored.
  762. _onModelEvent: function(event, model, collection, options) {
  763. if ((event === 'add' || event === 'remove') && collection !== this) return;
  764. if (event === 'destroy') this.remove(model, options);
  765. if (model && event === 'change:' + model.idAttribute) {
  766. delete this._byId[model.previous(model.idAttribute)];
  767. if (model.id != null) this._byId[model.id] = model;
  768. }
  769. this.trigger.apply(this, arguments);
  770. },
  771. sortedIndex: function (model, value, context) {
  772. value || (value = this.comparator);
  773. var iterator = _.isFunction(value) ? value : function(model) {
  774. return model.get(value);
  775. };
  776. return _.sortedIndex(this.models, model, iterator, context);
  777. }
  778. });
  779. // Underscore methods that we want to implement on the Collection.
  780. var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
  781. 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
  782. 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
  783. 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest',
  784. 'tail', 'drop', 'last', 'without', 'indexOf', 'shuffle', 'lastIndexOf',
  785. 'isEmpty', 'chain'];
  786. // Mix in each Underscore method as a proxy to `Collection#models`.
  787. _.each(methods, function(method) {
  788. Collection.prototype[method] = function() {
  789. var args = slice.call(arguments);
  790. args.unshift(this.models);
  791. return _[method].apply(_, args);
  792. };
  793. });
  794. // Underscore methods that take a property name as an argument.
  795. var attributeMethods = ['groupBy', 'countBy', 'sortBy'];
  796. // Use attributes instead of properties.
  797. _.each(attributeMethods, function(method) {
  798. Collection.prototype[method] = function(value, context) {
  799. var iterator = _.isFunction(value) ? value : function(model) {
  800. return model.get(value);
  801. };
  802. return _[method](this.models, iterator, context);
  803. };
  804. });
  805. // Backbone.Router
  806. // ---------------
  807. // Routers map faux-URLs to actions, and fire events when routes are
  808. // matched. Creating a new one sets its `routes` hash, if not set statically.
  809. var Router = Backbone.Router = function(options) {
  810. options || (options = {});
  811. if (options.routes) this.routes = options.routes;
  812. this._bindRoutes();
  813. this.initialize.apply(this, arguments);
  814. };
  815. // Cached regular expressions for matching named param parts and splatted
  816. // parts of route strings.
  817. var optionalParam = /\((.*?)\)/g;
  818. var namedParam = /(\(\?)?:\w+/g;
  819. var splatParam = /\*\w+/g;
  820. var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
  821. // Set up all inheritable **Backbone.Router** properties and methods.
  822. _.extend(Router.prototype, Events, {
  823. // Initialize is an empty function by default. Override it with your own
  824. // initialization logic.
  825. initialize: function(){},
  826. // Manually bind a single named route to a callback. For example:
  827. //
  828. // this.route('search/:query/p:num', 'search', function(query, num) {
  829. // ...
  830. // });
  831. //
  832. route: function(route, name, callback) {
  833. if (!_.isRegExp(route)) route = this._routeToRegExp(route);
  834. if (!callback) callback = this[name];
  835. Backbone.history.route(route, _.bind(function(fragment) {
  836. var args = this._extractParameters(route, fragment);
  837. callback && callback.apply(this, args);
  838. this.trigger.apply(this, ['route:' + name].concat(args));
  839. this.trigger('route', name, args);
  840. Backbone.history.trigger('route', this, name, args);
  841. }, this));
  842. return this;
  843. },
  844. // Simple proxy to `Backbone.history` to save a fragment into the history.
  845. navigate: function(fragment, options) {
  846. Backbone.history.navigate(fragment, options);
  847. return this;
  848. },
  849. // Bind all defined routes to `Backbone.history`. We have to reverse the
  850. // order of the routes here to support behavior where the most general
  851. // routes can be defined at the bottom of the route map.
  852. _bindRoutes: function() {
  853. if (!this.routes) return;
  854. var route, routes = _.keys(this.routes);
  855. while ((route = routes.pop()) != null) {
  856. this.route(route, this.routes[route]);
  857. }
  858. },
  859. // Convert a route string into a regular expression, suitable for matching
  860. // against the current location hash.
  861. _routeToRegExp: function(route) {
  862. route = route.replace(escapeRegExp, '\\$&')
  863. .replace(optionalParam, '(?:$1)?')
  864. .replace(namedParam, function(match, optional){
  865. return optional ? match : '([^\/]+)';
  866. })
  867. .replace(splatParam, '(.*?)');
  868. return new RegExp('^' + route + '$');
  869. },
  870. // Given a route, and a URL fragment that it matches, return the array of
  871. // extracted parameters.
  872. _extractParameters: function(route, fragment) {
  873. return route.exec(fragment).slice(1);
  874. }
  875. });
  876. // Backbone.History
  877. // ----------------
  878. // Handles cross-browser history management, based on URL fragments. If the
  879. // browser does not support `onhashchange`, falls back to polling.
  880. var History = Backbone.History = function() {
  881. this.handlers = [];
  882. _.bindAll(this, 'checkUrl');
  883. // Ensure that `History` can be used outside of the browser.
  884. if (typeof window !== 'undefined') {
  885. this.location = window.location;
  886. this.history = window.history;
  887. }
  888. };
  889. // Cached regex for stripping a leading hash/slash and trailing space.
  890. var routeStripper = /^[#\/]|\s+$/g;
  891. // Cached regex for stripping leading and trailing slashes.
  892. var rootStripper = /^\/+|\/+$/g;
  893. // Cached regex for detecting MSIE.
  894. var isExplorer = /msie [\w.]+/;
  895. // Cached regex for removing a trailing slash.
  896. var trailingSlash = /\/$/;
  897. // Has the history handling already been started?
  898. History.started = false;
  899. // Set up all inheritable **Backbone.History** properties and methods.
  900. _.extend(History.prototype, Events, {
  901. // The default interval to poll for hash changes, if necessary, is
  902. // twenty times a second.
  903. interval: 50,
  904. // Gets the true hash value. Cannot use location.hash directly due to bug
  905. // in Firefox where location.hash will always be decoded.
  906. getHash: function(window) {
  907. var match = (window || this).location.href.match(/#(.*)$/);
  908. return match ? match[1] : '';
  909. },
  910. // Get the cross-browser normalized URL fragment, either from the URL,
  911. // the hash, or the override.
  912. getFragment: function(fragment, forcePushState) {
  913. if (fragment == null) {
  914. if (this._hasPushState || !this._wantsHashChange || forcePushState) {
  915. fragment = this.location.pathname;
  916. var root = this.root.replace(trailingSlash, '');
  917. if (!fragment.indexOf(root)) fragment = fragment.substr(root.length);
  918. } else {
  919. fragment = this.getHash();
  920. }
  921. }
  922. return fragment.replace(routeStripper, '');
  923. },
  924. // Start the hash change handling, returning `true` if the current URL matches
  925. // an existing route, and `false` otherwise.
  926. start: function(options) {
  927. if (History.started) throw new Error("Backbone.history has already been started");
  928. History.started = true;
  929. // Figure out the initial configuration. Do we need an iframe?
  930. // Is pushState desired ... is it available?
  931. this.options = _.extend({}, {root: '/'}, this.options, options);
  932. this.root = this.options.root;
  933. this._wantsHashChange = this.options.hashChange !== false;
  934. this._wantsPushState = !!this.options.pushState;
  935. this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
  936. var fragment = this.getFragment();
  937. var docMode = document.documentMode;
  938. var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
  939. // Normalize root to always include a leading and trailing slash.
  940. this.root = ('/' + this.root + '/').replace(rootStripper, '/');
  941. if (oldIE && this._wantsHashChange) {
  942. this.iframe = Backbone.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
  943. this.navigate(fragment);
  944. }
  945. // Depending on whether we're using pushState or hashes, and whether
  946. // 'onhashchange' is supported, determine how we check the URL state.
  947. if (this._hasPushState) {
  948. Backbone.$(window).on('popstate', this.checkUrl);
  949. } else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
  950. Backbone.$(window).on('hashchange', this.checkUrl);
  951. } else if (this._wantsHashChange) {
  952. this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
  953. }
  954. // Determine if we need to change the base url, for a pushState link
  955. // opened by a non-pushState browser.
  956. this.fragment = fragment;
  957. var loc = this.location;
  958. var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;
  959. // If we've started off with a route from a `pushState`-enabled browser,
  960. // but we're currently in a browser that doesn't support it...
  961. if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) {
  962. this.fragment = this.getFragment(null, true);
  963. this.location.replace(this.root + this.location.search + '#' + this.fragment);
  964. // Return immediately as browser will do redirect to new url
  965. return true;
  966. // Or if we've started out with a hash-based route, but we're currently
  967. // in a browser where it could be `pushState`-based instead...
  968. } else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
  969. this.fragment = this.getHash().replace(routeStripper, '');
  970. this.history.replaceState({}, document.title, this.root + this.fragment + loc.search);
  971. }
  972. if (!this.options.silent) return this.loadUrl();
  973. },
  974. // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
  975. // but possibly useful for unit testing Routers.
  976. stop: function() {
  977. Backbone.$(window).off('popstate', this.checkUrl).off('hashchange', this.checkUrl);
  978. clearInterval(this._checkUrlInterval);
  979. History.started = false;
  980. },
  981. // Add a route to be tested when the fragment changes. Routes added later
  982. // may override previous routes.
  983. route: function(route, callback) {
  984. this.handlers.unshift({route: route, callback: callback});
  985. },
  986. // Checks the current URL to see if it has changed, and if it has,
  987. // calls `loadUrl`, normalizing across the hidden iframe.
  988. checkUrl: function(e) {
  989. var current = this.getFragment();
  990. if (current === this.fragment && this.iframe) {
  991. current = this.getFragment(this.getHash(this.iframe));
  992. }
  993. if (current === this.fragment) return false;
  994. if (this.iframe) this.navigate(current);
  995. this.loadUrl() || this.loadUrl(this.getHash());
  996. },
  997. // Attempt to load the current URL fragment. If a route succeeds with a
  998. // match, returns `true`. If no defined routes matches the fragment,
  999. // returns `false`.
  1000. loadUrl: function(fragmentOverride) {
  1001. var fragment = this.fragment = this.getFragment(fragmentOverride);
  1002. var matched = _.any(this.handlers, function(handler) {
  1003. if (handler.route.test(fragment)) {
  1004. handler.callback(fragment);
  1005. return true;
  1006. }
  1007. });
  1008. return matched;
  1009. },
  1010. // Save a fragment into the hash history, or replace the URL state if the
  1011. // 'replace' option is passed. You are responsible for properly URL-encoding
  1012. // the fragment in advance.
  1013. //
  1014. // The options object can contain `trigger: true` if you wish to have the
  1015. // route callback be fired (not usually desirable), or `replace: true`, if
  1016. // you wish to modify the current URL without adding an entry to the history.
  1017. navigate: function(fragment, options) {
  1018. if (!History.started) return false;
  1019. if (!options || options === true) options = {trigger: options};
  1020. fragment = this.getFragment(fragment || '');
  1021. if (this.fragment === fragment) return;
  1022. this.fragment = fragment;
  1023. var url = this.root + fragment;
  1024. // If pushState is available, we use it to set the fragment as a real URL.
  1025. if (this._hasPushState) {
  1026. this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
  1027. // If hash changes haven't been explicitly disabled, update the hash
  1028. // fragment to store history.
  1029. } else if (this._wantsHashChange) {
  1030. this._updateHash(this.location, fragment, options.replace);
  1031. if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) {
  1032. // Opening and closing the iframe tricks IE7 and earlier to push a
  1033. // history entry on hash-tag change. When replace is true, we don't
  1034. // want this.
  1035. if(!options.replace) this.iframe.document.open().close();
  1036. this._updateHash(this.iframe.location, fragment, options.replace);
  1037. }
  1038. // If you've told us that you explicitly don't want fallback hashchange-
  1039. // based history, then `navigate` becomes a page refresh.
  1040. } else {
  1041. return this.location.assign(url);
  1042. }
  1043. if (options.trigger) this.loadUrl(fragment);
  1044. },
  1045. // Update the hash location, either replacing the current entry, or adding
  1046. // a new one to the browser history.
  1047. _updateHash: function(location, fragment, replace) {
  1048. if (replace) {
  1049. var href = location.href.replace(/(javascript:|#).*$/, '');
  1050. location.replace(href + '#' + fragment);
  1051. } else {
  1052. // Some browsers require that `hash` contains a leading #.
  1053. location.hash = '#' + fragment;
  1054. }
  1055. }
  1056. });
  1057. // Create the default Backbone.history.
  1058. Backbone.history = new History;
  1059. // Backbone.View
  1060. // -------------
  1061. // Creating a Backbone.View creates its initial element outside of the DOM,
  1062. // if an existing element is not provided...
  1063. var View = Backbone.View = function(options) {
  1064. this.cid = _.uniqueId('view');
  1065. this._configure(options || {});
  1066. this._ensureElement();
  1067. this.initialize.apply(this, arguments);
  1068. this.delegateEvents();
  1069. };
  1070. // Cached regex to split keys for `delegate`.
  1071. var delegateEventSplitter = /^(\S+)\s*(.*)$/;
  1072. // List of view options to be merged as properties.
  1073. var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
  1074. // Set up all inheritable **Backbone.View** properties and methods.
  1075. _.extend(View.prototype, Events, {
  1076. // The default `tagName` of a View's element is `"div"`.
  1077. tagName: 'div',
  1078. // jQuery delegate for element lookup, scoped to DOM elements within the
  1079. // current view. This should be prefered to global lookups where possible.
  1080. $: function(selector) {
  1081. return this.$el.find(selector);
  1082. },
  1083. // Initialize is an empty function by default. Override it with your own
  1084. // initialization logic.
  1085. initialize: function(){},
  1086. // **render** is the core function that your view should override, in order
  1087. // to populate its element (`this.el`), with the appropriate HTML. The
  1088. // convention is for **render** to always return `this`.
  1089. render: function() {
  1090. return this;
  1091. },
  1092. // Remove this view by taking the element out of the DOM, and removing any
  1093. // applicable Backbone.Events listeners.
  1094. remove: function() {
  1095. this.$el.remove();
  1096. this.stopListening();
  1097. return this;
  1098. },
  1099. // Change the view's element (`this.el` property), including event
  1100. // re-delegation.
  1101. setElement: function(element, delegate) {
  1102. if (this.$el) this.undelegateEvents();
  1103. this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
  1104. this.el = this.$el[0];
  1105. if (delegate !== false) this.delegateEvents();
  1106. return this;
  1107. },
  1108. // Set callbacks, where `this.events` is a hash of
  1109. //
  1110. // *{"event selector": "callback"}*
  1111. //
  1112. // {
  1113. // 'mousedown .title': 'edit',
  1114. // 'click .button': 'save'
  1115. // 'click .open': function(e) { ... }
  1116. // }
  1117. //
  1118. // pairs. Callbacks will be bound to the view, with `this` set properly.
  1119. // Uses event delegation for efficiency.
  1120. // Omitting the selector binds the event to `this.el`.
  1121. // This only works for delegate-able events: not `focus`, `blur`, and
  1122. // not `change`, `submit`, and `reset` in Internet Explorer.
  1123. delegateEvents: function(events) {
  1124. if (!(events || (events = _.result(this, 'events')))) return this;
  1125. this.undelegateEvents();
  1126. for (var key in events) {
  1127. var method = events[key];
  1128. if (!_.isFunction(method)) method = this[events[key]];
  1129. if (!method) throw new Error('Method "' + events[key] + '" does not exist');
  1130. var match = key.match(delegateEventSplitter);
  1131. var eventName = match[1], selector = match[2];
  1132. method = _.bind(method, this);
  1133. eventName += '.delegateEvents' + this.cid;
  1134. if (selector === '') {
  1135. this.$el.on(eventName, method);
  1136. } else {
  1137. this.$el.on(eventName, selector, method);
  1138. }
  1139. }
  1140. return this;
  1141. },
  1142. // Clears all callbacks previously bound to the view with `delegateEvents`.
  1143. // You usually don't need to use this, but may wish to if you have multiple
  1144. // Backbone views attached to the same DOM element.
  1145. undelegateEvents: function() {
  1146. this.$el.off('.delegateEvents' + this.cid);
  1147. return this;
  1148. },
  1149. // Performs the initial configuration of a View with a set of options.
  1150. // Keys with special meaning *(model, collection, id, className)*, are
  1151. // attached directly to the view.
  1152. _configure: function(options) {
  1153. if (this.options) options = _.extend({}, _.result(this, 'options'), options);
  1154. _.extend(this, _.pick(options, viewOptions));
  1155. this.options = options;
  1156. },
  1157. // Ensure that the View has a DOM element to render into.
  1158. // If `this.el` is a string, pass it through `$()`, take the first
  1159. // matching element, and re-assign it to `el`. Otherwise, create
  1160. // an element from the `id`, `className` and `tagName` properties.
  1161. _ensureElement: function() {
  1162. if (!this.el) {
  1163. var attrs = _.extend({}, _.result(this, 'attributes'));
  1164. if (this.id) attrs.id = _.result(this, 'id');
  1165. if (this.className) attrs['class'] = _.result(this, 'className');
  1166. var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
  1167. this.setElement($el, false);
  1168. } else {
  1169. this.setElement(_.result(this, 'el'), false);
  1170. }
  1171. }
  1172. });
  1173. // Backbone.sync
  1174. // -------------
  1175. // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
  1176. var methodMap = {
  1177. 'create': 'POST',
  1178. 'update': 'PUT',
  1179. 'patch': 'PATCH',
  1180. 'delete': 'DELETE',
  1181. 'read': 'GET'
  1182. };
  1183. // Override this function to change the manner in which Backbone persists
  1184. // models to the server. You will be passed the type of request, and the
  1185. // model in question. By default, makes a RESTful Ajax request
  1186. // to the model's `url()`. Some possible customizations could be:
  1187. //
  1188. // * Use `setTimeout` to batch rapid-fire updates into a single request.
  1189. // * Send up the models as XML instead of JSON.
  1190. // * Persist models via WebSockets instead of Ajax.
  1191. //
  1192. // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
  1193. // as `POST`, with a `_method` parameter containing the true HTTP method,
  1194. // as well as all requests with the body as `application/x-www-form-urlencoded`
  1195. // instead of `application/json` with the model in a param named `model`.
  1196. // Useful when interfacing with server-side languages like **PHP** that make
  1197. // it difficult to read the body of `PUT` requests.
  1198. Backbone.sync = function(method, model, options) {
  1199. var type = methodMap[method];
  1200. // Default options, unless specified.
  1201. _.defaults(options || (options = {}), {
  1202. emulateHTTP: Backbone.emulateHTTP,
  1203. emulateJSON: Backbone.emulateJSON
  1204. });
  1205. // Default JSON-request options.
  1206. var params = {type: type, dataType: 'json'};
  1207. // Ensure that we have a URL.
  1208. if (!options.url) {
  1209. params.url = _.result(model, 'url') || urlError();
  1210. }
  1211. // Ensure that we have the appropriate request data.
  1212. if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
  1213. params.contentType = 'application/json';
  1214. params.data = JSON.stringify(options.attrs || model.toJSON(options));
  1215. }
  1216. // For older servers, emulate JSON by encoding the request into an HTML-form.
  1217. if (options.emulateJSON) {
  1218. params.contentType = 'application/x-www-form-urlencoded';
  1219. params.data = params.data ? {model: params.data} : {};
  1220. }
  1221. // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
  1222. // And an `X-HTTP-Method-Override` header.
  1223. if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
  1224. params.type = 'POST';
  1225. if (options.emulateJSON) params.data._method = type;
  1226. var beforeSend = options.beforeSend;
  1227. options.beforeSend = function(xhr) {
  1228. xhr.setRequestHeader('X-HTTP-Method-Override', type);
  1229. if (beforeSend) return beforeSend.apply(this, arguments);
  1230. };
  1231. }
  1232. // Don't process data on a non-GET request.
  1233. if (params.type !== 'GET' && !options.emulateJSON) {
  1234. params.processData = false;
  1235. }
  1236. // Make the request, allowing the user to override any Ajax options.
  1237. var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
  1238. model.trigger('request', model, xhr, options);
  1239. return xhr;
  1240. };
  1241. // Set the default implementation of `Backbone.ajax` to proxy through to `$`.
  1242. Backbone.ajax = function() {
  1243. return Backbone.$.ajax.apply(Backbone.$, arguments);
  1244. };
  1245. // Helpers
  1246. // -------
  1247. // Helper function to correctly set up the prototype chain, for subclasses.
  1248. // Similar to `goog.inherits`, but uses a hash of prototype properties and
  1249. // class properties to be extended.
  1250. var extend = function(protoProps, staticProps) {
  1251. var parent = this;
  1252. var child;
  1253. // The constructor function for the new subclass is either defined by you
  1254. // (the "constructor" property in your `extend` definition), or defaulted
  1255. // by us to simply call the parent's constructor.
  1256. if (protoProps && _.has(protoProps, 'constructor')) {
  1257. child = protoProps.constructor;
  1258. } else {
  1259. child = function(){ return parent.apply(this, arguments); };
  1260. }
  1261. // Add static properties to the constructor function, if supplied.
  1262. _.extend(child, parent, staticProps);
  1263. // Set the prototype chain to inherit from `parent`, without calling
  1264. // `parent`'s constructor function.
  1265. var Surrogate = function(){ this.constructor = child; };
  1266. Surrogate.prototype = parent.prototype;
  1267. child.prototype = new Surrogate;
  1268. // Add prototype properties (instance properties) to the subclass,
  1269. // if supplied.
  1270. if (protoProps) _.extend(child.prototype, protoProps);
  1271. // Set a convenience property in case the parent's prototype is needed
  1272. // later.
  1273. child.__super__ = parent.prototype;
  1274. return child;
  1275. };
  1276. // Set up inheritance for the model, collection, router, view and history.
  1277. Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
  1278. // Throw an error when a URL is needed, and none is supplied.
  1279. var urlError = function() {
  1280. throw new Error('A "url" property or function must be specified');
  1281. };
  1282. // Wrap an optional error callback with a fallback error event.
  1283. var wrapError = function (model, options) {
  1284. var error = options.error;
  1285. options.error = function(resp) {
  1286. if (error) error(model, resp, options);
  1287. model.trigger('error', model, resp, options);
  1288. };
  1289. };
  1290. }).call(this);