marionette-modal 1.0.0.8

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