annotate core/assets/vendor/backbone/backbone.js @ 19:fa3358dc1485 tip

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