ultimate-helpers 0.1.0.0

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