prop_up 0.0.1 → 0.0.2

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