rack-noncache 0.0.4 → 1.0.0

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