PageRenderTime 54ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/test/fixtures/json2_backbone.js

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