js_stack 0.5.7 → 0.6.0

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