annotate src/DML/VendorAssetsBundle/Resources/assets/backbone/1.1.2_modif/backbone.js @ 1:f38015048f48 tip

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