rails-assets-backbone 1.2.1

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