gokart 0.0.4 → 0.0.5

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