js-rails 0.1.0 → 0.2.0

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