tolaria 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (219) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +66 -0
  3. data/.yardopts +4 -0
  4. data/CNAME +1 -0
  5. data/CONTRIBUTING.md +32 -0
  6. data/Gemfile +2 -0
  7. data/LICENSE.md +9 -0
  8. data/README.md +538 -0
  9. data/Rakefile +52 -0
  10. data/app/assets/fonts/admin/fontawesome.eot +0 -0
  11. data/app/assets/fonts/admin/fontawesome.svg +565 -0
  12. data/app/assets/fonts/admin/fontawesome.ttf +0 -0
  13. data/app/assets/fonts/admin/fontawesome.woff +0 -0
  14. data/app/assets/fonts/admin/fontawesome.woff2 +0 -0
  15. data/app/assets/images/admin/columbia_banner.png +0 -0
  16. data/app/assets/images/admin/favicon.ico +0 -0
  17. data/app/assets/images/admin/noise.png +0 -0
  18. data/app/assets/images/admin/select_arrows.svg +1 -0
  19. data/app/assets/javascripts/admin/admin.js +4 -0
  20. data/app/assets/javascripts/admin/base.js +12 -0
  21. data/app/assets/javascripts/admin/lib/backbone.js +1888 -0
  22. data/app/assets/javascripts/admin/lib/jquery.chosen.js +1272 -0
  23. data/app/assets/javascripts/admin/lib/jquery.js +10361 -0
  24. data/app/assets/javascripts/admin/lib/jquery.selection.js +352 -0
  25. data/app/assets/javascripts/admin/lib/moment.js +3103 -0
  26. data/app/assets/javascripts/admin/lib/no.js +6 -0
  27. data/app/assets/javascripts/admin/lib/underscore.js +1570 -0
  28. data/app/assets/javascripts/admin/models/composer_buttons.js +45 -0
  29. data/app/assets/javascripts/admin/models/rails_meta.js +4 -0
  30. data/app/assets/javascripts/admin/views/field_with_errors.js +19 -0
  31. data/app/assets/javascripts/admin/views/fields/attachment_field.js +32 -0
  32. data/app/assets/javascripts/admin/views/fields/has_many.js +64 -0
  33. data/app/assets/javascripts/admin/views/fields/image_association_select.js +31 -0
  34. data/app/assets/javascripts/admin/views/fields/markdown_composer.js +167 -0
  35. data/app/assets/javascripts/admin/views/fields/searchable_select.js +70 -0
  36. data/app/assets/javascripts/admin/views/fields/slug_field.js +38 -0
  37. data/app/assets/javascripts/admin/views/fields/swatch_field.js +55 -0
  38. data/app/assets/javascripts/admin/views/fields/timestamp_field.js +80 -0
  39. data/app/assets/javascripts/admin/views/flash_message.js +18 -0
  40. data/app/assets/javascripts/admin/views/form_orchestrator.js +41 -0
  41. data/app/assets/javascripts/admin/views/navigation.js +20 -0
  42. data/app/assets/javascripts/admin/views/resource_form.js +18 -0
  43. data/app/assets/javascripts/admin/views/search_form.js +20 -0
  44. data/app/assets/javascripts/admin/views/sessions.js +109 -0
  45. data/app/assets/javascripts/admin/views/virtual_form.js +47 -0
  46. data/app/assets/stylesheets/admin/_base.scss +5 -0
  47. data/app/assets/stylesheets/admin/_reset.scss +149 -0
  48. data/app/assets/stylesheets/admin/_root.scss +63 -0
  49. data/app/assets/stylesheets/admin/admin.scss +4 -0
  50. data/app/assets/stylesheets/admin/components/_blank_slate.scss +44 -0
  51. data/app/assets/stylesheets/admin/components/_buttons.scss +82 -0
  52. data/app/assets/stylesheets/admin/components/_flash_message.scss +64 -0
  53. data/app/assets/stylesheets/admin/components/_footer.scss +9 -0
  54. data/app/assets/stylesheets/admin/components/_header.scss +107 -0
  55. data/app/assets/stylesheets/admin/components/_index_table.scss +120 -0
  56. data/app/assets/stylesheets/admin/components/_main.scss +68 -0
  57. data/app/assets/stylesheets/admin/components/_markdown_body.scss +109 -0
  58. data/app/assets/stylesheets/admin/components/_navigation.scss +110 -0
  59. data/app/assets/stylesheets/admin/components/_pagination.scss +36 -0
  60. data/app/assets/stylesheets/admin/components/_pill.scss +11 -0
  61. data/app/assets/stylesheets/admin/components/_resource_form.scss +222 -0
  62. data/app/assets/stylesheets/admin/components/_search_form.scss +36 -0
  63. data/app/assets/stylesheets/admin/components/_sessions.scss +152 -0
  64. data/app/assets/stylesheets/admin/components/_show_table.scss +67 -0
  65. data/app/assets/stylesheets/admin/components/forms/_attachment_field.scss +59 -0
  66. data/app/assets/stylesheets/admin/components/forms/_chosen.scss +478 -0
  67. data/app/assets/stylesheets/admin/components/forms/_image_association_select.scss +20 -0
  68. data/app/assets/stylesheets/admin/components/forms/_markdown_composer.scss +149 -0
  69. data/app/assets/stylesheets/admin/components/forms/_nested_fields.scss +63 -0
  70. data/app/assets/stylesheets/admin/components/forms/_searchable_select.scss +8 -0
  71. data/app/assets/stylesheets/admin/components/forms/_slug_field.scss +20 -0
  72. data/app/assets/stylesheets/admin/components/forms/_swatch_field.scss +47 -0
  73. data/app/assets/stylesheets/admin/components/forms/_timestamp_field.scss +15 -0
  74. data/app/assets/stylesheets/admin/components/help_link.scss +6 -0
  75. data/app/assets/stylesheets/admin/mixins/_clearfix.scss +18 -0
  76. data/app/assets/stylesheets/admin/mixins/_min_max_width.scss +11 -0
  77. data/app/assets/stylesheets/admin/mixins/_rgbb.scss +7 -0
  78. data/app/assets/stylesheets/admin/mixins/_visuallyhidden.scss +33 -0
  79. data/app/assets/stylesheets/admin/settings/_animations.scss +21 -0
  80. data/app/assets/stylesheets/admin/settings/_breakpoints.scss +2 -0
  81. data/app/assets/stylesheets/admin/settings/_colors.scss +32 -0
  82. data/app/assets/stylesheets/admin/settings/_fonts.scss +31 -0
  83. data/app/assets/stylesheets/admin/settings/_icons.scss +1658 -0
  84. data/app/controllers/admin/admin_controller.rb +21 -0
  85. data/app/controllers/admin/sessions_controller.rb +112 -0
  86. data/app/controllers/tolaria/resource_controller.rb +132 -0
  87. data/app/controllers/tolaria/tolaria_controller.rb +40 -0
  88. data/app/helpers/admin/table_helper.rb +175 -0
  89. data/app/helpers/admin/view_helper.rb +76 -0
  90. data/app/mailers/passcode_mailer.rb +11 -0
  91. data/app/models/administrator.rb +146 -0
  92. data/app/views/admin/administrators/_form.html.erb +16 -0
  93. data/app/views/admin/administrators/_index.html.erb +20 -0
  94. data/app/views/admin/administrators/_search.html.erb +5 -0
  95. data/app/views/admin/administrators/_show.html.erb +14 -0
  96. data/app/views/admin/help/help_link.html.erb +16 -0
  97. data/app/views/admin/session/form.html.erb +52 -0
  98. data/app/views/admin/shared/_flash_messages.html.erb +42 -0
  99. data/app/views/admin/shared/_footer.html.erb +8 -0
  100. data/app/views/admin/shared/_head.html.erb +11 -0
  101. data/app/views/admin/shared/_header.html.erb +43 -0
  102. data/app/views/admin/shared/_navigation.html.erb +47 -0
  103. data/app/views/admin/shared/_skiplinks.html.erb +0 -0
  104. data/app/views/admin/shared/forms/_attachment_field.html.erb +17 -0
  105. data/app/views/admin/shared/forms/_has_many.html.erb +14 -0
  106. data/app/views/admin/shared/forms/_has_many_header.html.erb +19 -0
  107. data/app/views/admin/shared/forms/_image_association_select.html.erb +6 -0
  108. data/app/views/admin/shared/forms/_image_field.html.erb +19 -0
  109. data/app/views/admin/shared/forms/_markdown_composer.html.erb +29 -0
  110. data/app/views/admin/shared/forms/_searchable_select.html.erb +3 -0
  111. data/app/views/admin/shared/forms/_slug_field.html.erb +9 -0
  112. data/app/views/admin/shared/forms/_swatch_field.html.erb +4 -0
  113. data/app/views/admin/shared/forms/_timestamp_field.html.erb +19 -0
  114. data/app/views/admin/tolaria_resource/_form_buttons.html.erb +10 -0
  115. data/app/views/admin/tolaria_resource/_index_table.html.erb +73 -0
  116. data/app/views/admin/tolaria_resource/_search_form.html.erb +32 -0
  117. data/app/views/admin/tolaria_resource/_show_buttons.html.erb +13 -0
  118. data/app/views/admin/tolaria_resource/edit.html.erb +34 -0
  119. data/app/views/admin/tolaria_resource/index.html.erb +36 -0
  120. data/app/views/admin/tolaria_resource/new.html.erb +1 -0
  121. data/app/views/admin/tolaria_resource/show.html.erb +52 -0
  122. data/app/views/kaminari/admin/_first_page.html.erb +9 -0
  123. data/app/views/kaminari/admin/_last_page.html.erb +9 -0
  124. data/app/views/kaminari/admin/_next_page.html.erb +9 -0
  125. data/app/views/kaminari/admin/_page.html.erb +17 -0
  126. data/app/views/kaminari/admin/_paginator.html.erb +21 -0
  127. data/app/views/kaminari/admin/_prev_page.html.erb +9 -0
  128. data/app/views/layouts/admin/admin.html.erb +21 -0
  129. data/app/views/layouts/admin/sessions.html.erb +12 -0
  130. data/app/views/passcode_mailer/passcode.text.erb +5 -0
  131. data/lib/generators/tolaria/install/install_generator.rb +21 -0
  132. data/lib/generators/tolaria/install/templates/administrators_migration.rb +31 -0
  133. data/lib/generators/tolaria/install/templates/tolaria_initializer.rb +93 -0
  134. data/lib/tasks/admin.rake +32 -0
  135. data/lib/tolaria.rb +27 -0
  136. data/lib/tolaria/active_record.rb +55 -0
  137. data/lib/tolaria/admin.rb +4 -0
  138. data/lib/tolaria/categories.rb +21 -0
  139. data/lib/tolaria/config.rb +40 -0
  140. data/lib/tolaria/default_config.rb +74 -0
  141. data/lib/tolaria/engine.rb +23 -0
  142. data/lib/tolaria/form_buildable.rb +203 -0
  143. data/lib/tolaria/help_links.rb +78 -0
  144. data/lib/tolaria/introspection.rb +13 -0
  145. data/lib/tolaria/manage.rb +57 -0
  146. data/lib/tolaria/managed_class.rb +90 -0
  147. data/lib/tolaria/markdown.rb +28 -0
  148. data/lib/tolaria/random_tokens.rb +16 -0
  149. data/lib/tolaria/reload.rb +21 -0
  150. data/lib/tolaria/routes.rb +33 -0
  151. data/lib/tolaria/version.rb +13 -0
  152. data/test/demo/Rakefile +4 -0
  153. data/test/demo/app/assets/javascripts/application.js +1 -0
  154. data/test/demo/app/assets/stylesheets/application.scss +1 -0
  155. data/test/demo/app/controllers/application_controller.rb +5 -0
  156. data/test/demo/app/controllers/concerns/.keep +0 -0
  157. data/test/demo/app/controllers/homepage_controller.rb +4 -0
  158. data/test/demo/app/helpers/application_helper.rb +2 -0
  159. data/test/demo/app/mailers/.keep +0 -0
  160. data/test/demo/app/models/.keep +0 -0
  161. data/test/demo/app/models/blog_post.rb +43 -0
  162. data/test/demo/app/models/footnote.rb +5 -0
  163. data/test/demo/app/models/image.rb +19 -0
  164. data/test/demo/app/models/legal_page.rb +24 -0
  165. data/test/demo/app/models/miscellany.rb +12 -0
  166. data/test/demo/app/models/topic.rb +22 -0
  167. data/test/demo/app/models/video.rb +16 -0
  168. data/test/demo/app/views/admin/blog_posts/_form.html.erb +48 -0
  169. data/test/demo/app/views/admin/blog_posts/_search.html.erb +5 -0
  170. data/test/demo/app/views/admin/help/markdown-help.md +95 -0
  171. data/test/demo/app/views/admin/images/_form.html.erb +26 -0
  172. data/test/demo/app/views/admin/legal_pages/_form.html.erb +15 -0
  173. data/test/demo/app/views/admin/topics/_form.html.erb +3 -0
  174. data/test/demo/app/views/admin/videos/_form.html.erb +11 -0
  175. data/test/demo/app/views/homepage/homepage.html.erb +3 -0
  176. data/test/demo/app/views/layouts/application.html.erb +14 -0
  177. data/test/demo/bin/bundle +3 -0
  178. data/test/demo/bin/rails +4 -0
  179. data/test/demo/bin/rake +4 -0
  180. data/test/demo/bin/setup +29 -0
  181. data/test/demo/config.ru +4 -0
  182. data/test/demo/config/application.rb +26 -0
  183. data/test/demo/config/boot.rb +4 -0
  184. data/test/demo/config/database.yml +18 -0
  185. data/test/demo/config/environment.rb +3 -0
  186. data/test/demo/config/environments/development.rb +43 -0
  187. data/test/demo/config/environments/test.rb +44 -0
  188. data/test/demo/config/initializers/assets.rb +11 -0
  189. data/test/demo/config/initializers/cookies_serializer.rb +2 -0
  190. data/test/demo/config/initializers/filter_parameter_logging.rb +3 -0
  191. data/test/demo/config/initializers/inflections.rb +17 -0
  192. data/test/demo/config/initializers/markdown.rb +44 -0
  193. data/test/demo/config/initializers/secret_token.rb +2 -0
  194. data/test/demo/config/initializers/session_store.rb +2 -0
  195. data/test/demo/config/initializers/tolaria.rb +17 -0
  196. data/test/demo/config/initializers/wrap_parameters.rb +14 -0
  197. data/test/demo/config/routes.rb +4 -0
  198. data/test/demo/db/migrate/20150601202901_create_administrators.rb +31 -0
  199. data/test/demo/db/migrate/20150603204006_add_testing_models.rb +27 -0
  200. data/test/demo/db/migrate/20150609232013_create_footnotes.rb +10 -0
  201. data/test/demo/db/migrate/20150610135235_create_additional_demo_objects.rb +50 -0
  202. data/test/demo/db/schema.rb +112 -0
  203. data/test/demo/log/.keep +0 -0
  204. data/test/demo/public/404.html +67 -0
  205. data/test/demo/public/422.html +67 -0
  206. data/test/demo/public/500.html +66 -0
  207. data/test/demo/public/favicon.ico +0 -0
  208. data/test/integration/help_link_test.rb +73 -0
  209. data/test/integration/interface_test.rb +63 -0
  210. data/test/integration/router_test.rb +73 -0
  211. data/test/integration/session_test.rb +88 -0
  212. data/test/test_helper.rb +58 -0
  213. data/test/unit/configuration_test.rb +21 -0
  214. data/test/unit/managed_classes_test.rb +54 -0
  215. data/test/unit/markdown_test.rb +12 -0
  216. data/test/unit/menu_test.rb +32 -0
  217. data/test/unit/random_tokens_test.rb +13 -0
  218. data/tolaria.gemspec +35 -0
  219. metadata +499 -0
@@ -0,0 +1 @@
1
+ <svg width="16" height="22" viewBox="0 0 16 22" xmlns="http://www.w3.org/2000/svg"><g fill="none"><path d="M15 13h-14c-.547 0-1 .453-1 1 0 .266.109.516.297.703l7 7c.188.188.438.297.703.297.266 0 .516-.109.703-.297l7-7c.188-.188.297-.438.297-.703 0-.547-.453-1-1-1z" fill="#1683A6"/><path d="M1 9h14c.547 0 1-.453 1-1 0-.266-.109-.516-.297-.703l-7-7c-.188-.188-.438-.297-.703-.297-.266 0-.516.109-.703.297l-7 7c-.188.188-.297.438-.297.703 0 .547.453 1 1 1z" fill="#1583A6"/></g></svg>
@@ -0,0 +1,4 @@
1
+ // To override, create app/assets/admin/admin.js in your parent app.
2
+ // The actual manifest is stored in base.js.
3
+
4
+ //= require admin/base.js
@@ -0,0 +1,12 @@
1
+ //= require admin/lib/jquery
2
+ //= require admin/lib/jquery.selection
3
+ //= require admin/lib/jquery.chosen
4
+ //= require admin/lib/underscore
5
+ //= require admin/lib/backbone
6
+ //= require admin/lib/moment
7
+
8
+ //= require_directory ./models
9
+ //= require_directory ./views
10
+ //= require_directory ./views/fields
11
+
12
+ FormOrchestrator.initializeViewsOver("body");
@@ -0,0 +1,1888 @@
1
+ // Backbone 1.2.0
2
+ // https://github.com/jashkenas/backbone
3
+ //
4
+ // Copyright (c) Jeremy Ashkenas, DocumentCloud, and
5
+ // Investigative Reporters & Editors
6
+ //
7
+ // Permission is hereby granted, free of charge, to any person
8
+ // obtaining a copy of this software and associated documentation
9
+ // files (the "Software"), to deal in the Software without
10
+ // restriction, including without limitation the rights to use,
11
+ // copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ // copies of the Software, and to permit persons to whom the
13
+ // Software is furnished to do so, subject to the following
14
+ // conditions:
15
+ //
16
+ // The above copyright notice and this permission notice shall be
17
+ // included in all copies or substantial portions of the Software.
18
+ //
19
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20
+ // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
21
+ // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
22
+ // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
23
+ // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
24
+ // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
25
+ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
26
+ // OTHER DEALINGS IN THE SOFTWARE.
27
+
28
+ (function(factory) {
29
+
30
+ // Establish the root object, `window` (`self`) in the browser, or `global` on the server.
31
+ // We use `self` instead of `window` for `WebWorker` support.
32
+ var root = (typeof self == 'object' && self.self == self && self) ||
33
+ (typeof global == 'object' && global.global == global && global);
34
+
35
+ // Set up Backbone appropriately for the environment. Start with AMD.
36
+ if (typeof define === 'function' && define.amd) {
37
+ define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
38
+ // Export global even in AMD case in case this script is loaded with
39
+ // others that may still expect a global Backbone.
40
+ root.Backbone = factory(root, exports, _, $);
41
+ });
42
+
43
+ // Next for Node.js or CommonJS. jQuery may not be needed as a module.
44
+ } else if (typeof exports !== 'undefined') {
45
+ var _ = require('underscore'), $;
46
+ try { $ = require('jquery'); } catch(e) {}
47
+ factory(root, exports, _, $);
48
+
49
+ // Finally, as a browser global.
50
+ } else {
51
+ root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$));
52
+ }
53
+
54
+ }(function(root, Backbone, _, $) {
55
+
56
+ // Initial Setup
57
+ // -------------
58
+
59
+ // Save the previous value of the `Backbone` variable, so that it can be
60
+ // restored later on, if `noConflict` is used.
61
+ var previousBackbone = root.Backbone;
62
+
63
+ // Create local references to array methods we'll want to use later.
64
+ var array = [];
65
+ var slice = array.slice;
66
+
67
+ // Current version of the library. Keep in sync with `package.json`.
68
+ Backbone.VERSION = '1.2.0';
69
+
70
+ // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
71
+ // the `$` variable.
72
+ Backbone.$ = $;
73
+
74
+ // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
75
+ // to its previous owner. Returns a reference to this Backbone object.
76
+ Backbone.noConflict = function() {
77
+ root.Backbone = previousBackbone;
78
+ return this;
79
+ };
80
+
81
+ // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
82
+ // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and
83
+ // set a `X-Http-Method-Override` header.
84
+ Backbone.emulateHTTP = false;
85
+
86
+ // Turn on `emulateJSON` to support legacy servers that can't deal with direct
87
+ // `application/json` requests ... this will encode the body as
88
+ // `application/x-www-form-urlencoded` instead and will send the model in a
89
+ // form param named `model`.
90
+ Backbone.emulateJSON = false;
91
+
92
+ // Backbone.Events
93
+ // ---------------
94
+
95
+ // A module that can be mixed in to *any object* in order to provide it with
96
+ // custom events. You may bind with `on` or remove with `off` callback
97
+ // functions to an event; `trigger`-ing an event fires all callbacks in
98
+ // succession.
99
+ //
100
+ // var object = {};
101
+ // _.extend(object, Backbone.Events);
102
+ // object.on('expand', function(){ alert('expanded'); });
103
+ // object.trigger('expand');
104
+ //
105
+ var Events = Backbone.Events = {};
106
+
107
+ // Regular expression used to split event strings.
108
+ var eventSplitter = /\s+/;
109
+
110
+ // Iterates over the standard `event, callback` (as well as the fancy multiple
111
+ // space-separated events `"change blur", callback` and jQuery-style event
112
+ // maps `{event: callback}`), reducing them by manipulating `memo`.
113
+ // Passes a normalized single event name and callback, as well as any
114
+ // optional `opts`.
115
+ var eventsApi = function(iteratee, memo, name, callback, opts) {
116
+ var i = 0, names;
117
+ if (name && typeof name === 'object') {
118
+ // Handle event maps.
119
+ for (names = _.keys(name); i < names.length ; i++) {
120
+ memo = iteratee(memo, names[i], name[names[i]], opts);
121
+ }
122
+ } else if (name && eventSplitter.test(name)) {
123
+ // Handle space separated event names.
124
+ for (names = name.split(eventSplitter); i < names.length; i++) {
125
+ memo = iteratee(memo, names[i], callback, opts);
126
+ }
127
+ } else {
128
+ memo = iteratee(memo, name, callback, opts);
129
+ }
130
+ return memo;
131
+ };
132
+
133
+ // Bind an event to a `callback` function. Passing `"all"` will bind
134
+ // the callback to all events fired.
135
+ Events.on = function(name, callback, context) {
136
+ return internalOn(this, name, callback, context);
137
+ };
138
+
139
+ // An internal use `on` function, used to guard the `listening` argument from
140
+ // the public API.
141
+ var internalOn = function(obj, name, callback, context, listening) {
142
+ obj._events = eventsApi(onApi, obj._events || {}, name, callback, {
143
+ context: context,
144
+ ctx: obj,
145
+ listening: listening
146
+ });
147
+
148
+ if (listening) {
149
+ var listeners = obj._listeners || (obj._listeners = {});
150
+ listeners[listening.id] = listening;
151
+ }
152
+
153
+ return obj;
154
+ };
155
+
156
+ // Inversion-of-control versions of `on`. Tell *this* object to listen to
157
+ // an event in another object... keeping track of what it's listening to.
158
+ Events.listenTo = function(obj, name, callback) {
159
+ if (!obj) return this;
160
+ var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
161
+ var listeningTo = this._listeningTo || (this._listeningTo = {});
162
+ var listening = listeningTo[id];
163
+
164
+ // This object is not listening to any other events on `obj` yet.
165
+ // Setup the necessary references to track the listening callbacks.
166
+ if (!listening) {
167
+ var thisId = this._listenId || (this._listenId = _.uniqueId('l'));
168
+ listening = listeningTo[id] = {obj: obj, objId: id, id: thisId, listeningTo: listeningTo, count: 0};
169
+ }
170
+
171
+ // Bind callbacks on obj, and keep track of them on listening.
172
+ internalOn(obj, name, callback, this, listening);
173
+ return this;
174
+ };
175
+
176
+ // The reducing API that adds a callback to the `events` object.
177
+ var onApi = function(events, name, callback, options) {
178
+ if (callback) {
179
+ var handlers = events[name] || (events[name] = []);
180
+ var context = options.context, ctx = options.ctx, listening = options.listening;
181
+ if (listening) listening.count++;
182
+
183
+ handlers.push({ callback: callback, context: context, ctx: context || ctx, listening: listening });
184
+ }
185
+ return events;
186
+ };
187
+
188
+ // Remove one or many callbacks. If `context` is null, removes all
189
+ // callbacks with that function. If `callback` is null, removes all
190
+ // callbacks for the event. If `name` is null, removes all bound
191
+ // callbacks for all events.
192
+ Events.off = function(name, callback, context) {
193
+ if (!this._events) return this;
194
+ this._events = eventsApi(offApi, this._events, name, callback, {
195
+ context: context,
196
+ listeners: this._listeners
197
+ });
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
+ Events.stopListening = function(obj, name, callback) {
204
+ var listeningTo = this._listeningTo;
205
+ if (!listeningTo) return this;
206
+
207
+ var ids = obj ? [obj._listenId] : _.keys(listeningTo);
208
+
209
+ for (var i = 0; i < ids.length; i++) {
210
+ var listening = listeningTo[ids[i]];
211
+
212
+ // If listening doesn't exist, this object is not currently
213
+ // listening to obj. Break out early.
214
+ if (!listening) break;
215
+
216
+ listening.obj.off(name, callback, this);
217
+ }
218
+ if (_.isEmpty(listeningTo)) this._listeningTo = void 0;
219
+
220
+ return this;
221
+ };
222
+
223
+ // The reducing API that removes a callback from the `events` object.
224
+ var offApi = function(events, name, callback, options) {
225
+ // No events to consider.
226
+ if (!events) return;
227
+
228
+ var i = 0, length, listening;
229
+ var context = options.context, listeners = options.listeners;
230
+
231
+ // Delete all events listeners and "drop" events.
232
+ if (!name && !callback && !context) {
233
+ var ids = _.keys(listeners);
234
+ for (; i < ids.length; i++) {
235
+ listening = listeners[ids[i]];
236
+ delete listeners[listening.id];
237
+ delete listening.listeningTo[listening.objId];
238
+ }
239
+ return;
240
+ }
241
+
242
+ var names = name ? [name] : _.keys(events);
243
+ for (; i < names.length; i++) {
244
+ name = names[i];
245
+ var handlers = events[name];
246
+
247
+ // Bail out if there are no events stored.
248
+ if (!handlers) break;
249
+
250
+ // Replace events if there are any remaining. Otherwise, clean up.
251
+ var remaining = [];
252
+ for (var j = 0; j < handlers.length; j++) {
253
+ var handler = handlers[j];
254
+ if (
255
+ callback && callback !== handler.callback &&
256
+ callback !== handler.callback._callback ||
257
+ context && context !== handler.context
258
+ ) {
259
+ remaining.push(handler);
260
+ } else {
261
+ listening = handler.listening;
262
+ if (listening && --listening.count === 0) {
263
+ delete listeners[listening.id];
264
+ delete listening.listeningTo[listening.objId];
265
+ }
266
+ }
267
+ }
268
+
269
+ // Update tail event if the list has any events. Otherwise, clean up.
270
+ if (remaining.length) {
271
+ events[name] = remaining;
272
+ } else {
273
+ delete events[name];
274
+ }
275
+ }
276
+ if (_.size(events)) return events;
277
+ };
278
+
279
+ // Bind an event to only be triggered a single time. After the first time
280
+ // the callback is invoked, it will be removed. When multiple events are
281
+ // passed in using the space-separated syntax, the event will fire once for every
282
+ // event you passed in, not once for a combination of all events
283
+ Events.once = function(name, callback, context) {
284
+ // Map the event into a `{event: once}` object.
285
+ var events = eventsApi(onceMap, {}, name, callback, _.bind(this.off, this));
286
+ return this.on(events, void 0, context);
287
+ };
288
+
289
+ // Inversion-of-control versions of `once`.
290
+ Events.listenToOnce = function(obj, name, callback) {
291
+ // Map the event into a `{event: once}` object.
292
+ var events = eventsApi(onceMap, {}, name, callback, _.bind(this.stopListening, this, obj));
293
+ return this.listenTo(obj, events);
294
+ };
295
+
296
+ // Reduces the event callbacks into a map of `{event: onceWrapper}`.
297
+ // `offer` unbinds the `onceWrapper` after it as been called.
298
+ var onceMap = function(map, name, callback, offer) {
299
+ if (callback) {
300
+ var once = map[name] = _.once(function() {
301
+ offer(name, once);
302
+ callback.apply(this, arguments);
303
+ });
304
+ once._callback = callback;
305
+ }
306
+ return map;
307
+ };
308
+
309
+ // Trigger one or many events, firing all bound callbacks. Callbacks are
310
+ // passed the same arguments as `trigger` is, apart from the event name
311
+ // (unless you're listening on `"all"`, which will cause your callback to
312
+ // receive the true name of the event as the first argument).
313
+ Events.trigger = function(name) {
314
+ if (!this._events) return this;
315
+
316
+ var length = Math.max(0, arguments.length - 1);
317
+ var args = Array(length);
318
+ for (var i = 0; i < length; i++) args[i] = arguments[i + 1];
319
+
320
+ eventsApi(triggerApi, this._events, name, void 0, args);
321
+ return this;
322
+ };
323
+
324
+ // Handles triggering the appropriate event callbacks.
325
+ var triggerApi = function(objEvents, name, cb, args) {
326
+ if (objEvents) {
327
+ var events = objEvents[name];
328
+ var allEvents = objEvents.all;
329
+ if (events && allEvents) allEvents = allEvents.slice();
330
+ if (events) triggerEvents(events, args);
331
+ if (allEvents) triggerEvents(allEvents, [name].concat(args));
332
+ }
333
+ return objEvents;
334
+ };
335
+
336
+ // A difficult-to-believe, but optimized internal dispatch function for
337
+ // triggering events. Tries to keep the usual cases speedy (most internal
338
+ // Backbone events have 3 arguments).
339
+ var triggerEvents = function(events, args) {
340
+ var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
341
+ switch (args.length) {
342
+ case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
343
+ case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
344
+ case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
345
+ case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
346
+ default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return;
347
+ }
348
+ };
349
+
350
+ // Proxy Underscore methods to a Backbone class' prototype using a
351
+ // particular attribute as the data argument
352
+ var addMethod = function(length, method, attribute) {
353
+ switch (length) {
354
+ case 1: return function() {
355
+ return _[method](this[attribute]);
356
+ };
357
+ case 2: return function(value) {
358
+ return _[method](this[attribute], value);
359
+ };
360
+ case 3: return function(iteratee, context) {
361
+ return _[method](this[attribute], iteratee, context);
362
+ };
363
+ case 4: return function(iteratee, defaultVal, context) {
364
+ return _[method](this[attribute], iteratee, defaultVal, context);
365
+ };
366
+ default: return function() {
367
+ var args = slice.call(arguments);
368
+ args.unshift(this[attribute]);
369
+ return _[method].apply(_, args);
370
+ };
371
+ }
372
+ };
373
+ var addUnderscoreMethods = function(Class, methods, attribute) {
374
+ _.each(methods, function(length, method) {
375
+ if (_[method]) Class.prototype[method] = addMethod(length, method, attribute);
376
+ });
377
+ };
378
+
379
+ // Aliases for backwards compatibility.
380
+ Events.bind = Events.on;
381
+ Events.unbind = Events.off;
382
+
383
+ // Allow the `Backbone` object to serve as a global event bus, for folks who
384
+ // want global "pubsub" in a convenient place.
385
+ _.extend(Backbone, Events);
386
+
387
+ // Backbone.Model
388
+ // --------------
389
+
390
+ // Backbone **Models** are the basic data object in the framework --
391
+ // frequently representing a row in a table in a database on your server.
392
+ // A discrete chunk of data and a bunch of useful, related methods for
393
+ // performing computations and transformations on that data.
394
+
395
+ // Create a new model with the specified attributes. A client id (`cid`)
396
+ // is automatically generated and assigned for you.
397
+ var Model = Backbone.Model = function(attributes, options) {
398
+ var attrs = attributes || {};
399
+ options || (options = {});
400
+ this.cid = _.uniqueId(this.cidPrefix);
401
+ this.attributes = {};
402
+ if (options.collection) this.collection = options.collection;
403
+ if (options.parse) attrs = this.parse(attrs, options) || {};
404
+ attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
405
+ this.set(attrs, options);
406
+ this.changed = {};
407
+ this.initialize.apply(this, arguments);
408
+ };
409
+
410
+ // Attach all inheritable methods to the Model prototype.
411
+ _.extend(Model.prototype, Events, {
412
+
413
+ // A hash of attributes whose current and previous value differ.
414
+ changed: null,
415
+
416
+ // The value returned during the last failed validation.
417
+ validationError: null,
418
+
419
+ // The default name for the JSON `id` attribute is `"id"`. MongoDB and
420
+ // CouchDB users may want to set this to `"_id"`.
421
+ idAttribute: 'id',
422
+
423
+ // The prefix is used to create the client id which is used to identify models locally.
424
+ // You may want to override this if you're experiencing name clashes with model ids.
425
+ cidPrefix: 'c',
426
+
427
+ // Initialize is an empty function by default. Override it with your own
428
+ // initialization logic.
429
+ initialize: function(){},
430
+
431
+ // Return a copy of the model's `attributes` object.
432
+ toJSON: function(options) {
433
+ return _.clone(this.attributes);
434
+ },
435
+
436
+ // Proxy `Backbone.sync` by default -- but override this if you need
437
+ // custom syncing semantics for *this* particular model.
438
+ sync: function() {
439
+ return Backbone.sync.apply(this, arguments);
440
+ },
441
+
442
+ // Get the value of an attribute.
443
+ get: function(attr) {
444
+ return this.attributes[attr];
445
+ },
446
+
447
+ // Get the HTML-escaped value of an attribute.
448
+ escape: function(attr) {
449
+ return _.escape(this.get(attr));
450
+ },
451
+
452
+ // Returns `true` if the attribute contains a value that is not null
453
+ // or undefined.
454
+ has: function(attr) {
455
+ return this.get(attr) != null;
456
+ },
457
+
458
+ // Special-cased proxy to underscore's `_.matches` method.
459
+ matches: function(attrs) {
460
+ return !!_.iteratee(attrs, this)(this.attributes);
461
+ },
462
+
463
+ // Set a hash of model attributes on the object, firing `"change"`. This is
464
+ // the core primitive operation of a model, updating the data and notifying
465
+ // anyone who needs to know about the change in state. The heart of the beast.
466
+ set: function(key, val, options) {
467
+ var attr, attrs, unset, changes, silent, changing, prev, current;
468
+ if (key == null) return this;
469
+
470
+ // Handle both `"key", value` and `{key: value}` -style arguments.
471
+ if (typeof key === 'object') {
472
+ attrs = key;
473
+ options = val;
474
+ } else {
475
+ (attrs = {})[key] = val;
476
+ }
477
+
478
+ options || (options = {});
479
+
480
+ // Run validation.
481
+ if (!this._validate(attrs, options)) return false;
482
+
483
+ // Extract attributes and options.
484
+ unset = options.unset;
485
+ silent = options.silent;
486
+ changes = [];
487
+ changing = this._changing;
488
+ this._changing = true;
489
+
490
+ if (!changing) {
491
+ this._previousAttributes = _.clone(this.attributes);
492
+ this.changed = {};
493
+ }
494
+ current = this.attributes, prev = this._previousAttributes;
495
+
496
+ // Check for changes of `id`.
497
+ if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
498
+
499
+ // For each `set` attribute, update or delete the current value.
500
+ for (attr in attrs) {
501
+ val = attrs[attr];
502
+ if (!_.isEqual(current[attr], val)) changes.push(attr);
503
+ if (!_.isEqual(prev[attr], val)) {
504
+ this.changed[attr] = val;
505
+ } else {
506
+ delete this.changed[attr];
507
+ }
508
+ unset ? delete current[attr] : current[attr] = val;
509
+ }
510
+
511
+ // Trigger all relevant attribute changes.
512
+ if (!silent) {
513
+ if (changes.length) this._pending = options;
514
+ for (var i = 0; i < changes.length; i++) {
515
+ this.trigger('change:' + changes[i], this, current[changes[i]], options);
516
+ }
517
+ }
518
+
519
+ // You might be wondering why there's a `while` loop here. Changes can
520
+ // be recursively nested within `"change"` events.
521
+ if (changing) return this;
522
+ if (!silent) {
523
+ while (this._pending) {
524
+ options = this._pending;
525
+ this._pending = false;
526
+ this.trigger('change', this, options);
527
+ }
528
+ }
529
+ this._pending = false;
530
+ this._changing = false;
531
+ return this;
532
+ },
533
+
534
+ // Remove an attribute from the model, firing `"change"`. `unset` is a noop
535
+ // if the attribute doesn't exist.
536
+ unset: function(attr, options) {
537
+ return this.set(attr, void 0, _.extend({}, options, {unset: true}));
538
+ },
539
+
540
+ // Clear all attributes on the model, firing `"change"`.
541
+ clear: function(options) {
542
+ var attrs = {};
543
+ for (var key in this.attributes) attrs[key] = void 0;
544
+ return this.set(attrs, _.extend({}, options, {unset: true}));
545
+ },
546
+
547
+ // Determine if the model has changed since the last `"change"` event.
548
+ // If you specify an attribute name, determine if that attribute has changed.
549
+ hasChanged: function(attr) {
550
+ if (attr == null) return !_.isEmpty(this.changed);
551
+ return _.has(this.changed, attr);
552
+ },
553
+
554
+ // Return an object containing all the attributes that have changed, or
555
+ // false if there are no changed attributes. Useful for determining what
556
+ // parts of a view need to be updated and/or what attributes need to be
557
+ // persisted to the server. Unset attributes will be set to undefined.
558
+ // You can also pass an attributes object to diff against the model,
559
+ // determining if there *would be* a change.
560
+ changedAttributes: function(diff) {
561
+ if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
562
+ var val, changed = false;
563
+ var old = this._changing ? this._previousAttributes : this.attributes;
564
+ for (var attr in diff) {
565
+ if (_.isEqual(old[attr], (val = diff[attr]))) continue;
566
+ (changed || (changed = {}))[attr] = val;
567
+ }
568
+ return changed;
569
+ },
570
+
571
+ // Get the previous value of an attribute, recorded at the time the last
572
+ // `"change"` event was fired.
573
+ previous: function(attr) {
574
+ if (attr == null || !this._previousAttributes) return null;
575
+ return this._previousAttributes[attr];
576
+ },
577
+
578
+ // Get all of the attributes of the model at the time of the previous
579
+ // `"change"` event.
580
+ previousAttributes: function() {
581
+ return _.clone(this._previousAttributes);
582
+ },
583
+
584
+ // Fetch the model from the server, merging the response with the model's
585
+ // local attributes. Any changed attributes will trigger a "change" event.
586
+ fetch: function(options) {
587
+ options = options ? _.clone(options) : {};
588
+ if (options.parse === void 0) options.parse = true;
589
+ var model = this;
590
+ var success = options.success;
591
+ options.success = function(resp) {
592
+ if (!model.set(model.parse(resp, options), options)) return false;
593
+ if (success) success.call(options.context, model, resp, options);
594
+ model.trigger('sync', model, resp, options);
595
+ };
596
+ wrapError(this, options);
597
+ return this.sync('read', this, options);
598
+ },
599
+
600
+ // Set a hash of model attributes, and sync the model to the server.
601
+ // If the server returns an attributes hash that differs, the model's
602
+ // state will be `set` again.
603
+ save: function(key, val, options) {
604
+ var attrs, method, xhr, attributes = this.attributes, wait;
605
+
606
+ // Handle both `"key", value` and `{key: value}` -style arguments.
607
+ if (key == null || typeof key === 'object') {
608
+ attrs = key;
609
+ options = val;
610
+ } else {
611
+ (attrs = {})[key] = val;
612
+ }
613
+
614
+ options = _.extend({validate: true}, options);
615
+ wait = options.wait;
616
+
617
+ // If we're not waiting and attributes exist, save acts as
618
+ // `set(attr).save(null, opts)` with validation. Otherwise, check if
619
+ // the model will be valid when the attributes, if any, are set.
620
+ if (attrs && !wait) {
621
+ if (!this.set(attrs, options)) return false;
622
+ } else {
623
+ if (!this._validate(attrs, options)) return false;
624
+ }
625
+
626
+ // Set temporary attributes if `{wait: true}`.
627
+ if (attrs && wait) {
628
+ this.attributes = _.extend({}, attributes, attrs);
629
+ }
630
+
631
+ // After a successful server-side save, the client is (optionally)
632
+ // updated with the server-side state.
633
+ if (options.parse === void 0) options.parse = true;
634
+ var model = this;
635
+ var success = options.success;
636
+ options.success = function(resp) {
637
+ // Ensure attributes are restored during synchronous saves.
638
+ model.attributes = attributes;
639
+ var serverAttrs = options.parse ? model.parse(resp, options) : resp;
640
+ if (wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
641
+ if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
642
+ return false;
643
+ }
644
+ if (success) success.call(options.context, model, resp, options);
645
+ model.trigger('sync', model, resp, options);
646
+ };
647
+ wrapError(this, options);
648
+
649
+ method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
650
+ if (method === 'patch' && !options.attrs) options.attrs = attrs;
651
+ xhr = this.sync(method, this, options);
652
+
653
+ // Restore attributes.
654
+ if (attrs && wait) this.attributes = attributes;
655
+
656
+ return xhr;
657
+ },
658
+
659
+ // Destroy this model on the server if it was already persisted.
660
+ // Optimistically removes the model from its collection, if it has one.
661
+ // If `wait: true` is passed, waits for the server to respond before removal.
662
+ destroy: function(options) {
663
+ options = options ? _.clone(options) : {};
664
+ var model = this;
665
+ var success = options.success;
666
+ var wait = options.wait;
667
+
668
+ var destroy = function() {
669
+ model.stopListening();
670
+ model.trigger('destroy', model, model.collection, options);
671
+ };
672
+
673
+ options.success = function(resp) {
674
+ if (wait) destroy();
675
+ if (success) success.call(options.context, model, resp, options);
676
+ if (!model.isNew()) model.trigger('sync', model, resp, options);
677
+ };
678
+
679
+ var xhr = false;
680
+ if (this.isNew()) {
681
+ _.defer(options.success);
682
+ } else {
683
+ wrapError(this, options);
684
+ xhr = this.sync('delete', this, options);
685
+ }
686
+ if (!wait) destroy();
687
+ return xhr;
688
+ },
689
+
690
+ // Default URL for the model's representation on the server -- if you're
691
+ // using Backbone's restful methods, override this to change the endpoint
692
+ // that will be called.
693
+ url: function() {
694
+ var base =
695
+ _.result(this, 'urlRoot') ||
696
+ _.result(this.collection, 'url') ||
697
+ urlError();
698
+ if (this.isNew()) return base;
699
+ var id = this.id || this.attributes[this.idAttribute];
700
+ return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(id);
701
+ },
702
+
703
+ // **parse** converts a response into the hash of attributes to be `set` on
704
+ // the model. The default implementation is just to pass the response along.
705
+ parse: function(resp, options) {
706
+ return resp;
707
+ },
708
+
709
+ // Create a new model with identical attributes to this one.
710
+ clone: function() {
711
+ return new this.constructor(this.attributes);
712
+ },
713
+
714
+ // A model is new if it has never been saved to the server, and lacks an id.
715
+ isNew: function() {
716
+ return !this.has(this.idAttribute);
717
+ },
718
+
719
+ // Check if the model is currently in a valid state.
720
+ isValid: function(options) {
721
+ return this._validate({}, _.extend(options || {}, { validate: true }));
722
+ },
723
+
724
+ // Run validation against the next complete set of model attributes,
725
+ // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
726
+ _validate: function(attrs, options) {
727
+ if (!options.validate || !this.validate) return true;
728
+ attrs = _.extend({}, this.attributes, attrs);
729
+ var error = this.validationError = this.validate(attrs, options) || null;
730
+ if (!error) return true;
731
+ this.trigger('invalid', this, error, _.extend(options, {validationError: error}));
732
+ return false;
733
+ }
734
+
735
+ });
736
+
737
+ // Underscore methods that we want to implement on the Model.
738
+ var modelMethods = { keys: 1, values: 1, pairs: 1, invert: 1, pick: 0,
739
+ omit: 0, chain: 1, isEmpty: 1 };
740
+
741
+ // Mix in each Underscore method as a proxy to `Model#attributes`.
742
+ addUnderscoreMethods(Model, modelMethods, 'attributes');
743
+
744
+ // Backbone.Collection
745
+ // -------------------
746
+
747
+ // If models tend to represent a single row of data, a Backbone Collection is
748
+ // more analogous to a table full of data ... or a small slice or page of that
749
+ // table, or a collection of rows that belong together for a particular reason
750
+ // -- all of the messages in this particular folder, all of the documents
751
+ // belonging to this particular author, and so on. Collections maintain
752
+ // indexes of their models, both in order, and for lookup by `id`.
753
+
754
+ // Create a new **Collection**, perhaps to contain a specific type of `model`.
755
+ // If a `comparator` is specified, the Collection will maintain
756
+ // its models in sort order, as they're added and removed.
757
+ var Collection = Backbone.Collection = function(models, options) {
758
+ options || (options = {});
759
+ if (options.model) this.model = options.model;
760
+ if (options.comparator !== void 0) this.comparator = options.comparator;
761
+ this._reset();
762
+ this.initialize.apply(this, arguments);
763
+ if (models) this.reset(models, _.extend({silent: true}, options));
764
+ };
765
+
766
+ // Default options for `Collection#set`.
767
+ var setOptions = {add: true, remove: true, merge: true};
768
+ var addOptions = {add: true, remove: false};
769
+
770
+ // Define the Collection's inheritable methods.
771
+ _.extend(Collection.prototype, Events, {
772
+
773
+ // The default model for a collection is just a **Backbone.Model**.
774
+ // This should be overridden in most cases.
775
+ model: Model,
776
+
777
+ // Initialize is an empty function by default. Override it with your own
778
+ // initialization logic.
779
+ initialize: function(){},
780
+
781
+ // The JSON representation of a Collection is an array of the
782
+ // models' attributes.
783
+ toJSON: function(options) {
784
+ return this.map(function(model){ return model.toJSON(options); });
785
+ },
786
+
787
+ // Proxy `Backbone.sync` by default.
788
+ sync: function() {
789
+ return Backbone.sync.apply(this, arguments);
790
+ },
791
+
792
+ // Add a model, or list of models to the set.
793
+ add: function(models, options) {
794
+ return this.set(models, _.extend({merge: false}, options, addOptions));
795
+ },
796
+
797
+ // Remove a model, or a list of models from the set.
798
+ remove: function(models, options) {
799
+ var singular = !_.isArray(models), removed;
800
+ models = singular ? [models] : _.clone(models);
801
+ options || (options = {});
802
+ removed = this._removeModels(models, options);
803
+ if (!options.silent && removed) this.trigger('update', this, options);
804
+ return singular ? models[0] : models;
805
+ },
806
+
807
+ // Update a collection by `set`-ing a new list of models, adding new ones,
808
+ // removing models that are no longer present, and merging models that
809
+ // already exist in the collection, as necessary. Similar to **Model#set**,
810
+ // the core operation for updating the data contained by the collection.
811
+ set: function(models, options) {
812
+ options = _.defaults({}, options, setOptions);
813
+ if (options.parse) models = this.parse(models, options);
814
+ var singular = !_.isArray(models);
815
+ models = singular ? (models ? [models] : []) : models.slice();
816
+ var id, model, attrs, existing, sort;
817
+ var at = options.at;
818
+ if (at != null) at = +at;
819
+ if (at < 0) at += this.length + 1;
820
+ var sortable = this.comparator && (at == null) && options.sort !== false;
821
+ var sortAttr = _.isString(this.comparator) ? this.comparator : null;
822
+ var toAdd = [], toRemove = [], modelMap = {};
823
+ var add = options.add, merge = options.merge, remove = options.remove;
824
+ var order = !sortable && add && remove ? [] : false;
825
+ var orderChanged = false;
826
+
827
+ // Turn bare objects into model references, and prevent invalid models
828
+ // from being added.
829
+ for (var i = 0; i < models.length; i++) {
830
+ attrs = models[i];
831
+
832
+ // If a duplicate is found, prevent it from being added and
833
+ // optionally merge it into the existing model.
834
+ if (existing = this.get(attrs)) {
835
+ if (remove) modelMap[existing.cid] = true;
836
+ if (merge && attrs !== existing) {
837
+ attrs = this._isModel(attrs) ? attrs.attributes : attrs;
838
+ if (options.parse) attrs = existing.parse(attrs, options);
839
+ existing.set(attrs, options);
840
+ if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
841
+ }
842
+ models[i] = existing;
843
+
844
+ // If this is a new, valid model, push it to the `toAdd` list.
845
+ } else if (add) {
846
+ model = models[i] = this._prepareModel(attrs, options);
847
+ if (!model) continue;
848
+ toAdd.push(model);
849
+ this._addReference(model, options);
850
+ }
851
+
852
+ // Do not add multiple models with the same `id`.
853
+ model = existing || model;
854
+ if (!model) continue;
855
+ id = this.modelId(model.attributes);
856
+ if (order && (model.isNew() || !modelMap[id])) {
857
+ order.push(model);
858
+
859
+ // Check to see if this is actually a new model at this index.
860
+ orderChanged = orderChanged || !this.models[i] || model.cid !== this.models[i].cid;
861
+ }
862
+
863
+ modelMap[id] = true;
864
+ }
865
+
866
+ // Remove nonexistent models if appropriate.
867
+ if (remove) {
868
+ for (var i = 0; i < this.length; i++) {
869
+ if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model);
870
+ }
871
+ if (toRemove.length) this._removeModels(toRemove, options);
872
+ }
873
+
874
+ // See if sorting is needed, update `length` and splice in new models.
875
+ if (toAdd.length || orderChanged) {
876
+ if (sortable) sort = true;
877
+ this.length += toAdd.length;
878
+ if (at != null) {
879
+ for (var i = 0; i < toAdd.length; i++) {
880
+ this.models.splice(at + i, 0, toAdd[i]);
881
+ }
882
+ } else {
883
+ if (order) this.models.length = 0;
884
+ var orderedModels = order || toAdd;
885
+ for (var i = 0; i < orderedModels.length; i++) {
886
+ this.models.push(orderedModels[i]);
887
+ }
888
+ }
889
+ }
890
+
891
+ // Silently sort the collection if appropriate.
892
+ if (sort) this.sort({silent: true});
893
+
894
+ // Unless silenced, it's time to fire all appropriate add/sort events.
895
+ if (!options.silent) {
896
+ var addOpts = at != null ? _.clone(options) : options;
897
+ for (var i = 0; i < toAdd.length; i++) {
898
+ if (at != null) addOpts.index = at + i;
899
+ (model = toAdd[i]).trigger('add', model, this, addOpts);
900
+ }
901
+ if (sort || orderChanged) this.trigger('sort', this, options);
902
+ if (toAdd.length || toRemove.length) this.trigger('update', this, options);
903
+ }
904
+
905
+ // Return the added (or merged) model (or models).
906
+ return singular ? models[0] : models;
907
+ },
908
+
909
+ // When you have more items than you want to add or remove individually,
910
+ // you can reset the entire set with a new list of models, without firing
911
+ // any granular `add` or `remove` events. Fires `reset` when finished.
912
+ // Useful for bulk operations and optimizations.
913
+ reset: function(models, options) {
914
+ options = options ? _.clone(options) : {};
915
+ for (var i = 0; i < this.models.length; i++) {
916
+ this._removeReference(this.models[i], options);
917
+ }
918
+ options.previousModels = this.models;
919
+ this._reset();
920
+ models = this.add(models, _.extend({silent: true}, options));
921
+ if (!options.silent) this.trigger('reset', this, options);
922
+ return models;
923
+ },
924
+
925
+ // Add a model to the end of the collection.
926
+ push: function(model, options) {
927
+ return this.add(model, _.extend({at: this.length}, options));
928
+ },
929
+
930
+ // Remove a model from the end of the collection.
931
+ pop: function(options) {
932
+ var model = this.at(this.length - 1);
933
+ this.remove(model, options);
934
+ return model;
935
+ },
936
+
937
+ // Add a model to the beginning of the collection.
938
+ unshift: function(model, options) {
939
+ return this.add(model, _.extend({at: 0}, options));
940
+ },
941
+
942
+ // Remove a model from the beginning of the collection.
943
+ shift: function(options) {
944
+ var model = this.at(0);
945
+ this.remove(model, options);
946
+ return model;
947
+ },
948
+
949
+ // Slice out a sub-array of models from the collection.
950
+ slice: function() {
951
+ return slice.apply(this.models, arguments);
952
+ },
953
+
954
+ // Get a model from the set by id.
955
+ get: function(obj) {
956
+ if (obj == null) return void 0;
957
+ var id = this.modelId(this._isModel(obj) ? obj.attributes : obj);
958
+ return this._byId[obj] || this._byId[id] || this._byId[obj.cid];
959
+ },
960
+
961
+ // Get the model at the given index.
962
+ at: function(index) {
963
+ if (index < 0) index += this.length;
964
+ return this.models[index];
965
+ },
966
+
967
+ // Return models with matching attributes. Useful for simple cases of
968
+ // `filter`.
969
+ where: function(attrs, first) {
970
+ var matches = _.matches(attrs);
971
+ return this[first ? 'find' : 'filter'](function(model) {
972
+ return matches(model.attributes);
973
+ });
974
+ },
975
+
976
+ // Return the first model with matching attributes. Useful for simple cases
977
+ // of `find`.
978
+ findWhere: function(attrs) {
979
+ return this.where(attrs, true);
980
+ },
981
+
982
+ // Force the collection to re-sort itself. You don't need to call this under
983
+ // normal circumstances, as the set will maintain sort order as each item
984
+ // is added.
985
+ sort: function(options) {
986
+ if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
987
+ options || (options = {});
988
+
989
+ // Run sort based on type of `comparator`.
990
+ if (_.isString(this.comparator) || this.comparator.length === 1) {
991
+ this.models = this.sortBy(this.comparator, this);
992
+ } else {
993
+ this.models.sort(_.bind(this.comparator, this));
994
+ }
995
+
996
+ if (!options.silent) this.trigger('sort', this, options);
997
+ return this;
998
+ },
999
+
1000
+ // Pluck an attribute from each model in the collection.
1001
+ pluck: function(attr) {
1002
+ return _.invoke(this.models, 'get', attr);
1003
+ },
1004
+
1005
+ // Fetch the default set of models for this collection, resetting the
1006
+ // collection when they arrive. If `reset: true` is passed, the response
1007
+ // data will be passed through the `reset` method instead of `set`.
1008
+ fetch: function(options) {
1009
+ options = options ? _.clone(options) : {};
1010
+ if (options.parse === void 0) options.parse = true;
1011
+ var success = options.success;
1012
+ var collection = this;
1013
+ options.success = function(resp) {
1014
+ var method = options.reset ? 'reset' : 'set';
1015
+ collection[method](resp, options);
1016
+ if (success) success.call(options.context, collection, resp, options);
1017
+ collection.trigger('sync', collection, resp, options);
1018
+ };
1019
+ wrapError(this, options);
1020
+ return this.sync('read', this, options);
1021
+ },
1022
+
1023
+ // Create a new instance of a model in this collection. Add the model to the
1024
+ // collection immediately, unless `wait: true` is passed, in which case we
1025
+ // wait for the server to agree.
1026
+ create: function(model, options) {
1027
+ options = options ? _.clone(options) : {};
1028
+ var wait = options.wait;
1029
+ if (!(model = this._prepareModel(model, options))) return false;
1030
+ if (!wait) this.add(model, options);
1031
+ var collection = this;
1032
+ var success = options.success;
1033
+ options.success = function(model, resp, callbackOpts) {
1034
+ if (wait) collection.add(model, callbackOpts);
1035
+ if (success) success.call(callbackOpts.context, model, resp, callbackOpts);
1036
+ };
1037
+ model.save(null, options);
1038
+ return model;
1039
+ },
1040
+
1041
+ // **parse** converts a response into a list of models to be added to the
1042
+ // collection. The default implementation is just to pass it through.
1043
+ parse: function(resp, options) {
1044
+ return resp;
1045
+ },
1046
+
1047
+ // Create a new collection with an identical list of models as this one.
1048
+ clone: function() {
1049
+ return new this.constructor(this.models, {
1050
+ model: this.model,
1051
+ comparator: this.comparator
1052
+ });
1053
+ },
1054
+
1055
+ // Define how to uniquely identify models in the collection.
1056
+ modelId: function (attrs) {
1057
+ return attrs[this.model.prototype.idAttribute || 'id'];
1058
+ },
1059
+
1060
+ // Private method to reset all internal state. Called when the collection
1061
+ // is first initialized or reset.
1062
+ _reset: function() {
1063
+ this.length = 0;
1064
+ this.models = [];
1065
+ this._byId = {};
1066
+ },
1067
+
1068
+ // Prepare a hash of attributes (or other model) to be added to this
1069
+ // collection.
1070
+ _prepareModel: function(attrs, options) {
1071
+ if (this._isModel(attrs)) {
1072
+ if (!attrs.collection) attrs.collection = this;
1073
+ return attrs;
1074
+ }
1075
+ options = options ? _.clone(options) : {};
1076
+ options.collection = this;
1077
+ var model = new this.model(attrs, options);
1078
+ if (!model.validationError) return model;
1079
+ this.trigger('invalid', this, model.validationError, options);
1080
+ return false;
1081
+ },
1082
+
1083
+ // Internal method called by both remove and set. Does not trigger any
1084
+ // additional events. Returns true if anything was actually removed.
1085
+ _removeModels: function(models, options) {
1086
+ var i, l, index, model, removed = false;
1087
+ for (var i = 0, j = 0; i < models.length; i++) {
1088
+ var model = models[i] = this.get(models[i]);
1089
+ if (!model) continue;
1090
+ var id = this.modelId(model.attributes);
1091
+ if (id != null) delete this._byId[id];
1092
+ delete this._byId[model.cid];
1093
+ var index = this.indexOf(model);
1094
+ this.models.splice(index, 1);
1095
+ this.length--;
1096
+ if (!options.silent) {
1097
+ options.index = index;
1098
+ model.trigger('remove', model, this, options);
1099
+ }
1100
+ models[j++] = model;
1101
+ this._removeReference(model, options);
1102
+ removed = true;
1103
+ }
1104
+ // We only need to slice if models array should be smaller, which is
1105
+ // caused by some models not actually getting removed.
1106
+ if (models.length !== j) models = models.slice(0, j);
1107
+ return removed;
1108
+ },
1109
+
1110
+ // Method for checking whether an object should be considered a model for
1111
+ // the purposes of adding to the collection.
1112
+ _isModel: function (model) {
1113
+ return model instanceof Model;
1114
+ },
1115
+
1116
+ // Internal method to create a model's ties to a collection.
1117
+ _addReference: function(model, options) {
1118
+ this._byId[model.cid] = model;
1119
+ var id = this.modelId(model.attributes);
1120
+ if (id != null) this._byId[id] = model;
1121
+ model.on('all', this._onModelEvent, this);
1122
+ },
1123
+
1124
+ // Internal method to sever a model's ties to a collection.
1125
+ _removeReference: function(model, options) {
1126
+ if (this === model.collection) delete model.collection;
1127
+ model.off('all', this._onModelEvent, this);
1128
+ },
1129
+
1130
+ // Internal method called every time a model in the set fires an event.
1131
+ // Sets need to update their indexes when models change ids. All other
1132
+ // events simply proxy through. "add" and "remove" events that originate
1133
+ // in other collections are ignored.
1134
+ _onModelEvent: function(event, model, collection, options) {
1135
+ if ((event === 'add' || event === 'remove') && collection !== this) return;
1136
+ if (event === 'destroy') this.remove(model, options);
1137
+ if (event === 'change') {
1138
+ var prevId = this.modelId(model.previousAttributes());
1139
+ var id = this.modelId(model.attributes);
1140
+ if (prevId !== id) {
1141
+ if (prevId != null) delete this._byId[prevId];
1142
+ if (id != null) this._byId[id] = model;
1143
+ }
1144
+ }
1145
+ this.trigger.apply(this, arguments);
1146
+ }
1147
+
1148
+ });
1149
+
1150
+ // Underscore methods that we want to implement on the Collection.
1151
+ // 90% of the core usefulness of Backbone Collections is actually implemented
1152
+ // right here:
1153
+ var collectionMethods = { forEach: 3, each: 3, map: 3, collect: 3, reduce: 4,
1154
+ foldl: 4, inject: 4, reduceRight: 4, foldr: 4, find: 3, detect: 3, filter: 3,
1155
+ select: 3, reject: 3, every: 3, all: 3, some: 3, any: 3, include: 2,
1156
+ contains: 2, invoke: 2, max: 3, min: 3, toArray: 1, size: 1, first: 3,
1157
+ head: 3, take: 3, initial: 3, rest: 3, tail: 3, drop: 3, last: 3,
1158
+ without: 0, difference: 0, indexOf: 3, shuffle: 1, lastIndexOf: 3,
1159
+ isEmpty: 1, chain: 1, sample: 3, partition: 3 };
1160
+
1161
+ // Mix in each Underscore method as a proxy to `Collection#models`.
1162
+ addUnderscoreMethods(Collection, collectionMethods, 'models');
1163
+
1164
+ // Underscore methods that take a property name as an argument.
1165
+ var attributeMethods = ['groupBy', 'countBy', 'sortBy', 'indexBy'];
1166
+
1167
+ // Use attributes instead of properties.
1168
+ _.each(attributeMethods, function(method) {
1169
+ if (!_[method]) return;
1170
+ Collection.prototype[method] = function(value, context) {
1171
+ var iterator = _.isFunction(value) ? value : function(model) {
1172
+ return model.get(value);
1173
+ };
1174
+ return _[method](this.models, iterator, context);
1175
+ };
1176
+ });
1177
+
1178
+ // Backbone.View
1179
+ // -------------
1180
+
1181
+ // Backbone Views are almost more convention than they are actual code. A View
1182
+ // is simply a JavaScript object that represents a logical chunk of UI in the
1183
+ // DOM. This might be a single item, an entire list, a sidebar or panel, or
1184
+ // even the surrounding frame which wraps your whole app. Defining a chunk of
1185
+ // UI as a **View** allows you to define your DOM events declaratively, without
1186
+ // having to worry about render order ... and makes it easy for the view to
1187
+ // react to specific changes in the state of your models.
1188
+
1189
+ // Creating a Backbone.View creates its initial element outside of the DOM,
1190
+ // if an existing element is not provided...
1191
+ var View = Backbone.View = function(options) {
1192
+ this.cid = _.uniqueId('view');
1193
+ options || (options = {});
1194
+ _.extend(this, _.pick(options, viewOptions));
1195
+ this._ensureElement();
1196
+ this.initialize.apply(this, arguments);
1197
+ };
1198
+
1199
+ // Cached regex to split keys for `delegate`.
1200
+ var delegateEventSplitter = /^(\S+)\s*(.*)$/;
1201
+
1202
+ // List of view options to be merged as properties.
1203
+ var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
1204
+
1205
+ // Set up all inheritable **Backbone.View** properties and methods.
1206
+ _.extend(View.prototype, Events, {
1207
+
1208
+ // The default `tagName` of a View's element is `"div"`.
1209
+ tagName: 'div',
1210
+
1211
+ // jQuery delegate for element lookup, scoped to DOM elements within the
1212
+ // current view. This should be preferred to global lookups where possible.
1213
+ $: function(selector) {
1214
+ return this.$el.find(selector);
1215
+ },
1216
+
1217
+ // Initialize is an empty function by default. Override it with your own
1218
+ // initialization logic.
1219
+ initialize: function(){},
1220
+
1221
+ // **render** is the core function that your view should override, in order
1222
+ // to populate its element (`this.el`), with the appropriate HTML. The
1223
+ // convention is for **render** to always return `this`.
1224
+ render: function() {
1225
+ return this;
1226
+ },
1227
+
1228
+ // Remove this view by taking the element out of the DOM, and removing any
1229
+ // applicable Backbone.Events listeners.
1230
+ remove: function() {
1231
+ this._removeElement();
1232
+ this.stopListening();
1233
+ return this;
1234
+ },
1235
+
1236
+ // Remove this view's element from the document and all event listeners
1237
+ // attached to it. Exposed for subclasses using an alternative DOM
1238
+ // manipulation API.
1239
+ _removeElement: function() {
1240
+ this.$el.remove();
1241
+ },
1242
+
1243
+ // Change the view's element (`this.el` property) and re-delegate the
1244
+ // view's events on the new element.
1245
+ setElement: function(element) {
1246
+ this.undelegateEvents();
1247
+ this._setElement(element);
1248
+ this.delegateEvents();
1249
+ return this;
1250
+ },
1251
+
1252
+ // Creates the `this.el` and `this.$el` references for this view using the
1253
+ // given `el`. `el` can be a CSS selector or an HTML string, a jQuery
1254
+ // context or an element. Subclasses can override this to utilize an
1255
+ // alternative DOM manipulation API and are only required to set the
1256
+ // `this.el` property.
1257
+ _setElement: function(el) {
1258
+ this.$el = el instanceof Backbone.$ ? el : Backbone.$(el);
1259
+ this.el = this.$el[0];
1260
+ },
1261
+
1262
+ // Set callbacks, where `this.events` is a hash of
1263
+ //
1264
+ // *{"event selector": "callback"}*
1265
+ //
1266
+ // {
1267
+ // 'mousedown .title': 'edit',
1268
+ // 'click .button': 'save',
1269
+ // 'click .open': function(e) { ... }
1270
+ // }
1271
+ //
1272
+ // pairs. Callbacks will be bound to the view, with `this` set properly.
1273
+ // Uses event delegation for efficiency.
1274
+ // Omitting the selector binds the event to `this.el`.
1275
+ delegateEvents: function(events) {
1276
+ if (!(events || (events = _.result(this, 'events')))) return this;
1277
+ this.undelegateEvents();
1278
+ for (var key in events) {
1279
+ var method = events[key];
1280
+ if (!_.isFunction(method)) method = this[events[key]];
1281
+ if (!method) continue;
1282
+ var match = key.match(delegateEventSplitter);
1283
+ this.delegate(match[1], match[2], _.bind(method, this));
1284
+ }
1285
+ return this;
1286
+ },
1287
+
1288
+ // Add a single event listener to the view's element (or a child element
1289
+ // using `selector`). This only works for delegate-able events: not `focus`,
1290
+ // `blur`, and not `change`, `submit`, and `reset` in Internet Explorer.
1291
+ delegate: function(eventName, selector, listener) {
1292
+ this.$el.on(eventName + '.delegateEvents' + this.cid, selector, listener);
1293
+ },
1294
+
1295
+ // Clears all callbacks previously bound to the view by `delegateEvents`.
1296
+ // You usually don't need to use this, but may wish to if you have multiple
1297
+ // Backbone views attached to the same DOM element.
1298
+ undelegateEvents: function() {
1299
+ if (this.$el) this.$el.off('.delegateEvents' + this.cid);
1300
+ return this;
1301
+ },
1302
+
1303
+ // A finer-grained `undelegateEvents` for removing a single delegated event.
1304
+ // `selector` and `listener` are both optional.
1305
+ undelegate: function(eventName, selector, listener) {
1306
+ this.$el.off(eventName + '.delegateEvents' + this.cid, selector, listener);
1307
+ },
1308
+
1309
+ // Produces a DOM element to be assigned to your view. Exposed for
1310
+ // subclasses using an alternative DOM manipulation API.
1311
+ _createElement: function(tagName) {
1312
+ return document.createElement(tagName);
1313
+ },
1314
+
1315
+ // Ensure that the View has a DOM element to render into.
1316
+ // If `this.el` is a string, pass it through `$()`, take the first
1317
+ // matching element, and re-assign it to `el`. Otherwise, create
1318
+ // an element from the `id`, `className` and `tagName` properties.
1319
+ _ensureElement: function() {
1320
+ if (!this.el) {
1321
+ var attrs = _.extend({}, _.result(this, 'attributes'));
1322
+ if (this.id) attrs.id = _.result(this, 'id');
1323
+ if (this.className) attrs['class'] = _.result(this, 'className');
1324
+ this.setElement(this._createElement(_.result(this, 'tagName')));
1325
+ this._setAttributes(attrs);
1326
+ } else {
1327
+ this.setElement(_.result(this, 'el'));
1328
+ }
1329
+ },
1330
+
1331
+ // Set attributes from a hash on this view's element. Exposed for
1332
+ // subclasses using an alternative DOM manipulation API.
1333
+ _setAttributes: function(attributes) {
1334
+ this.$el.attr(attributes);
1335
+ }
1336
+
1337
+ });
1338
+
1339
+ // Backbone.sync
1340
+ // -------------
1341
+
1342
+ // Override this function to change the manner in which Backbone persists
1343
+ // models to the server. You will be passed the type of request, and the
1344
+ // model in question. By default, makes a RESTful Ajax request
1345
+ // to the model's `url()`. Some possible customizations could be:
1346
+ //
1347
+ // * Use `setTimeout` to batch rapid-fire updates into a single request.
1348
+ // * Send up the models as XML instead of JSON.
1349
+ // * Persist models via WebSockets instead of Ajax.
1350
+ //
1351
+ // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
1352
+ // as `POST`, with a `_method` parameter containing the true HTTP method,
1353
+ // as well as all requests with the body as `application/x-www-form-urlencoded`
1354
+ // instead of `application/json` with the model in a param named `model`.
1355
+ // Useful when interfacing with server-side languages like **PHP** that make
1356
+ // it difficult to read the body of `PUT` requests.
1357
+ Backbone.sync = function(method, model, options) {
1358
+ var type = methodMap[method];
1359
+
1360
+ // Default options, unless specified.
1361
+ _.defaults(options || (options = {}), {
1362
+ emulateHTTP: Backbone.emulateHTTP,
1363
+ emulateJSON: Backbone.emulateJSON
1364
+ });
1365
+
1366
+ // Default JSON-request options.
1367
+ var params = {type: type, dataType: 'json'};
1368
+
1369
+ // Ensure that we have a URL.
1370
+ if (!options.url) {
1371
+ params.url = _.result(model, 'url') || urlError();
1372
+ }
1373
+
1374
+ // Ensure that we have the appropriate request data.
1375
+ if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
1376
+ params.contentType = 'application/json';
1377
+ params.data = JSON.stringify(options.attrs || model.toJSON(options));
1378
+ }
1379
+
1380
+ // For older servers, emulate JSON by encoding the request into an HTML-form.
1381
+ if (options.emulateJSON) {
1382
+ params.contentType = 'application/x-www-form-urlencoded';
1383
+ params.data = params.data ? {model: params.data} : {};
1384
+ }
1385
+
1386
+ // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
1387
+ // And an `X-HTTP-Method-Override` header.
1388
+ if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
1389
+ params.type = 'POST';
1390
+ if (options.emulateJSON) params.data._method = type;
1391
+ var beforeSend = options.beforeSend;
1392
+ options.beforeSend = function(xhr) {
1393
+ xhr.setRequestHeader('X-HTTP-Method-Override', type);
1394
+ if (beforeSend) return beforeSend.apply(this, arguments);
1395
+ };
1396
+ }
1397
+
1398
+ // Don't process data on a non-GET request.
1399
+ if (params.type !== 'GET' && !options.emulateJSON) {
1400
+ params.processData = false;
1401
+ }
1402
+
1403
+ // Pass along `textStatus` and `errorThrown` from jQuery.
1404
+ var error = options.error;
1405
+ options.error = function(xhr, textStatus, errorThrown) {
1406
+ options.textStatus = textStatus;
1407
+ options.errorThrown = errorThrown;
1408
+ if (error) error.call(options.context, xhr, textStatus, errorThrown);
1409
+ };
1410
+
1411
+ // Make the request, allowing the user to override any Ajax options.
1412
+ var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
1413
+ model.trigger('request', model, xhr, options);
1414
+ return xhr;
1415
+ };
1416
+
1417
+ // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
1418
+ var methodMap = {
1419
+ 'create': 'POST',
1420
+ 'update': 'PUT',
1421
+ 'patch': 'PATCH',
1422
+ 'delete': 'DELETE',
1423
+ 'read': 'GET'
1424
+ };
1425
+
1426
+ // Set the default implementation of `Backbone.ajax` to proxy through to `$`.
1427
+ // Override this if you'd like to use a different library.
1428
+ Backbone.ajax = function() {
1429
+ return Backbone.$.ajax.apply(Backbone.$, arguments);
1430
+ };
1431
+
1432
+ // Backbone.Router
1433
+ // ---------------
1434
+
1435
+ // Routers map faux-URLs to actions, and fire events when routes are
1436
+ // matched. Creating a new one sets its `routes` hash, if not set statically.
1437
+ var Router = Backbone.Router = function(options) {
1438
+ options || (options = {});
1439
+ if (options.routes) this.routes = options.routes;
1440
+ this._bindRoutes();
1441
+ this.initialize.apply(this, arguments);
1442
+ };
1443
+
1444
+ // Cached regular expressions for matching named param parts and splatted
1445
+ // parts of route strings.
1446
+ var optionalParam = /\((.*?)\)/g;
1447
+ var namedParam = /(\(\?)?:\w+/g;
1448
+ var splatParam = /\*\w+/g;
1449
+ var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
1450
+
1451
+ // Set up all inheritable **Backbone.Router** properties and methods.
1452
+ _.extend(Router.prototype, Events, {
1453
+
1454
+ // Initialize is an empty function by default. Override it with your own
1455
+ // initialization logic.
1456
+ initialize: function(){},
1457
+
1458
+ // Manually bind a single named route to a callback. For example:
1459
+ //
1460
+ // this.route('search/:query/p:num', 'search', function(query, num) {
1461
+ // ...
1462
+ // });
1463
+ //
1464
+ route: function(route, name, callback) {
1465
+ if (!_.isRegExp(route)) route = this._routeToRegExp(route);
1466
+ if (_.isFunction(name)) {
1467
+ callback = name;
1468
+ name = '';
1469
+ }
1470
+ if (!callback) callback = this[name];
1471
+ var router = this;
1472
+ Backbone.history.route(route, function(fragment) {
1473
+ var args = router._extractParameters(route, fragment);
1474
+ if (router.execute(callback, args, name) !== false) {
1475
+ router.trigger.apply(router, ['route:' + name].concat(args));
1476
+ router.trigger('route', name, args);
1477
+ Backbone.history.trigger('route', router, name, args);
1478
+ }
1479
+ });
1480
+ return this;
1481
+ },
1482
+
1483
+ // Execute a route handler with the provided parameters. This is an
1484
+ // excellent place to do pre-route setup or post-route cleanup.
1485
+ execute: function(callback, args, name) {
1486
+ if (callback) callback.apply(this, args);
1487
+ },
1488
+
1489
+ // Simple proxy to `Backbone.history` to save a fragment into the history.
1490
+ navigate: function(fragment, options) {
1491
+ Backbone.history.navigate(fragment, options);
1492
+ return this;
1493
+ },
1494
+
1495
+ // Bind all defined routes to `Backbone.history`. We have to reverse the
1496
+ // order of the routes here to support behavior where the most general
1497
+ // routes can be defined at the bottom of the route map.
1498
+ _bindRoutes: function() {
1499
+ if (!this.routes) return;
1500
+ this.routes = _.result(this, 'routes');
1501
+ var route, routes = _.keys(this.routes);
1502
+ while ((route = routes.pop()) != null) {
1503
+ this.route(route, this.routes[route]);
1504
+ }
1505
+ },
1506
+
1507
+ // Convert a route string into a regular expression, suitable for matching
1508
+ // against the current location hash.
1509
+ _routeToRegExp: function(route) {
1510
+ route = route.replace(escapeRegExp, '\\$&')
1511
+ .replace(optionalParam, '(?:$1)?')
1512
+ .replace(namedParam, function(match, optional) {
1513
+ return optional ? match : '([^/?]+)';
1514
+ })
1515
+ .replace(splatParam, '([^?]*?)');
1516
+ return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$');
1517
+ },
1518
+
1519
+ // Given a route, and a URL fragment that it matches, return the array of
1520
+ // extracted decoded parameters. Empty or unmatched parameters will be
1521
+ // treated as `null` to normalize cross-browser behavior.
1522
+ _extractParameters: function(route, fragment) {
1523
+ var params = route.exec(fragment).slice(1);
1524
+ return _.map(params, function(param, i) {
1525
+ // Don't decode the search params.
1526
+ if (i === params.length - 1) return param || null;
1527
+ return param ? decodeURIComponent(param) : null;
1528
+ });
1529
+ }
1530
+
1531
+ });
1532
+
1533
+ // Backbone.History
1534
+ // ----------------
1535
+
1536
+ // Handles cross-browser history management, based on either
1537
+ // [pushState](http://diveintohtml5.info/history.html) and real URLs, or
1538
+ // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
1539
+ // and URL fragments. If the browser supports neither (old IE, natch),
1540
+ // falls back to polling.
1541
+ var History = Backbone.History = function() {
1542
+ this.handlers = [];
1543
+ _.bindAll(this, 'checkUrl');
1544
+
1545
+ // Ensure that `History` can be used outside of the browser.
1546
+ if (typeof window !== 'undefined') {
1547
+ this.location = window.location;
1548
+ this.history = window.history;
1549
+ }
1550
+ };
1551
+
1552
+ // Cached regex for stripping a leading hash/slash and trailing space.
1553
+ var routeStripper = /^[#\/]|\s+$/g;
1554
+
1555
+ // Cached regex for stripping leading and trailing slashes.
1556
+ var rootStripper = /^\/+|\/+$/g;
1557
+
1558
+ // Cached regex for stripping urls of hash.
1559
+ var pathStripper = /#.*$/;
1560
+
1561
+ // Has the history handling already been started?
1562
+ History.started = false;
1563
+
1564
+ // Set up all inheritable **Backbone.History** properties and methods.
1565
+ _.extend(History.prototype, Events, {
1566
+
1567
+ // The default interval to poll for hash changes, if necessary, is
1568
+ // twenty times a second.
1569
+ interval: 50,
1570
+
1571
+ // Are we at the app root?
1572
+ atRoot: function() {
1573
+ var path = this.location.pathname.replace(/[^\/]$/, '$&/');
1574
+ return path === this.root && !this.getSearch();
1575
+ },
1576
+
1577
+ // Does the pathname match the root?
1578
+ matchRoot: function() {
1579
+ var path = this.decodeFragment(this.location.pathname);
1580
+ var root = path.slice(0, this.root.length - 1) + '/';
1581
+ return root === this.root;
1582
+ },
1583
+
1584
+ // Unicode characters in `location.pathname` are percent encoded so they're
1585
+ // decoded for comparison. `%25` should not be decoded since it may be part
1586
+ // of an encoded parameter.
1587
+ decodeFragment: function(fragment) {
1588
+ return decodeURI(fragment.replace(/%25/g, '%2525'));
1589
+ },
1590
+
1591
+ // In IE6, the hash fragment and search params are incorrect if the
1592
+ // fragment contains `?`.
1593
+ getSearch: function() {
1594
+ var match = this.location.href.replace(/#.*/, '').match(/\?.+/);
1595
+ return match ? match[0] : '';
1596
+ },
1597
+
1598
+ // Gets the true hash value. Cannot use location.hash directly due to bug
1599
+ // in Firefox where location.hash will always be decoded.
1600
+ getHash: function(window) {
1601
+ var match = (window || this).location.href.match(/#(.*)$/);
1602
+ return match ? match[1] : '';
1603
+ },
1604
+
1605
+ // Get the pathname and search params, without the root.
1606
+ getPath: function() {
1607
+ var path = this.decodeFragment(
1608
+ this.location.pathname + this.getSearch()
1609
+ ).slice(this.root.length - 1);
1610
+ return path.charAt(0) === '/' ? path.slice(1) : path;
1611
+ },
1612
+
1613
+ // Get the cross-browser normalized URL fragment from the path or hash.
1614
+ getFragment: function(fragment) {
1615
+ if (fragment == null) {
1616
+ if (this._usePushState || !this._wantsHashChange) {
1617
+ fragment = this.getPath();
1618
+ } else {
1619
+ fragment = this.getHash();
1620
+ }
1621
+ }
1622
+ return fragment.replace(routeStripper, '');
1623
+ },
1624
+
1625
+ // Start the hash change handling, returning `true` if the current URL matches
1626
+ // an existing route, and `false` otherwise.
1627
+ start: function(options) {
1628
+ if (History.started) throw new Error('Backbone.history has already been started');
1629
+ History.started = true;
1630
+
1631
+ // Figure out the initial configuration. Do we need an iframe?
1632
+ // Is pushState desired ... is it available?
1633
+ this.options = _.extend({root: '/'}, this.options, options);
1634
+ this.root = this.options.root;
1635
+ this._wantsHashChange = this.options.hashChange !== false;
1636
+ this._hasHashChange = 'onhashchange' in window;
1637
+ this._useHashChange = this._wantsHashChange && this._hasHashChange;
1638
+ this._wantsPushState = !!this.options.pushState;
1639
+ this._hasPushState = !!(this.history && this.history.pushState);
1640
+ this._usePushState = this._wantsPushState && this._hasPushState;
1641
+ this.fragment = this.getFragment();
1642
+
1643
+ // Normalize root to always include a leading and trailing slash.
1644
+ this.root = ('/' + this.root + '/').replace(rootStripper, '/');
1645
+
1646
+ // Transition from hashChange to pushState or vice versa if both are
1647
+ // requested.
1648
+ if (this._wantsHashChange && this._wantsPushState) {
1649
+
1650
+ // If we've started off with a route from a `pushState`-enabled
1651
+ // browser, but we're currently in a browser that doesn't support it...
1652
+ if (!this._hasPushState && !this.atRoot()) {
1653
+ var root = this.root.slice(0, -1) || '/';
1654
+ this.location.replace(root + '#' + this.getPath());
1655
+ // Return immediately as browser will do redirect to new url
1656
+ return true;
1657
+
1658
+ // Or if we've started out with a hash-based route, but we're currently
1659
+ // in a browser where it could be `pushState`-based instead...
1660
+ } else if (this._hasPushState && this.atRoot()) {
1661
+ this.navigate(this.getHash(), {replace: true});
1662
+ }
1663
+
1664
+ }
1665
+
1666
+ // Proxy an iframe to handle location events if the browser doesn't
1667
+ // support the `hashchange` event, HTML5 history, or the user wants
1668
+ // `hashChange` but not `pushState`.
1669
+ if (!this._hasHashChange && this._wantsHashChange && !this._usePushState) {
1670
+ var iframe = document.createElement('iframe');
1671
+ iframe.src = 'javascript:0';
1672
+ iframe.style.display = 'none';
1673
+ iframe.tabIndex = -1;
1674
+ var body = document.body;
1675
+ // Using `appendChild` will throw on IE < 9 if the document is not ready.
1676
+ this.iframe = body.insertBefore(iframe, body.firstChild).contentWindow;
1677
+ this.iframe.document.open().close();
1678
+ this.iframe.location.hash = '#' + this.fragment;
1679
+ }
1680
+
1681
+ // Add a cross-platform `addEventListener` shim for older browsers.
1682
+ var addEventListener = window.addEventListener || function (eventName, listener) {
1683
+ return attachEvent('on' + eventName, listener);
1684
+ };
1685
+
1686
+ // Depending on whether we're using pushState or hashes, and whether
1687
+ // 'onhashchange' is supported, determine how we check the URL state.
1688
+ if (this._usePushState) {
1689
+ addEventListener('popstate', this.checkUrl, false);
1690
+ } else if (this._useHashChange && !this.iframe) {
1691
+ addEventListener('hashchange', this.checkUrl, false);
1692
+ } else if (this._wantsHashChange) {
1693
+ this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
1694
+ }
1695
+
1696
+ if (!this.options.silent) return this.loadUrl();
1697
+ },
1698
+
1699
+ // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
1700
+ // but possibly useful for unit testing Routers.
1701
+ stop: function() {
1702
+ // Add a cross-platform `removeEventListener` shim for older browsers.
1703
+ var removeEventListener = window.removeEventListener || function (eventName, listener) {
1704
+ return detachEvent('on' + eventName, listener);
1705
+ };
1706
+
1707
+ // Remove window listeners.
1708
+ if (this._usePushState) {
1709
+ removeEventListener('popstate', this.checkUrl, false);
1710
+ } else if (this._useHashChange && !this.iframe) {
1711
+ removeEventListener('hashchange', this.checkUrl, false);
1712
+ }
1713
+
1714
+ // Clean up the iframe if necessary.
1715
+ if (this.iframe) {
1716
+ document.body.removeChild(this.iframe.frameElement);
1717
+ this.iframe = null;
1718
+ }
1719
+
1720
+ // Some environments will throw when clearing an undefined interval.
1721
+ if (this._checkUrlInterval) clearInterval(this._checkUrlInterval);
1722
+ History.started = false;
1723
+ },
1724
+
1725
+ // Add a route to be tested when the fragment changes. Routes added later
1726
+ // may override previous routes.
1727
+ route: function(route, callback) {
1728
+ this.handlers.unshift({route: route, callback: callback});
1729
+ },
1730
+
1731
+ // Checks the current URL to see if it has changed, and if it has,
1732
+ // calls `loadUrl`, normalizing across the hidden iframe.
1733
+ checkUrl: function(e) {
1734
+ var current = this.getFragment();
1735
+
1736
+ // If the user pressed the back button, the iframe's hash will have
1737
+ // changed and we should use that for comparison.
1738
+ if (current === this.fragment && this.iframe) {
1739
+ current = this.getHash(this.iframe);
1740
+ }
1741
+
1742
+ if (current === this.fragment) return false;
1743
+ if (this.iframe) this.navigate(current);
1744
+ this.loadUrl();
1745
+ },
1746
+
1747
+ // Attempt to load the current URL fragment. If a route succeeds with a
1748
+ // match, returns `true`. If no defined routes matches the fragment,
1749
+ // returns `false`.
1750
+ loadUrl: function(fragment) {
1751
+ // If the root doesn't match, no routes can match either.
1752
+ if (!this.matchRoot()) return false;
1753
+ fragment = this.fragment = this.getFragment(fragment);
1754
+ return _.any(this.handlers, function(handler) {
1755
+ if (handler.route.test(fragment)) {
1756
+ handler.callback(fragment);
1757
+ return true;
1758
+ }
1759
+ });
1760
+ },
1761
+
1762
+ // Save a fragment into the hash history, or replace the URL state if the
1763
+ // 'replace' option is passed. You are responsible for properly URL-encoding
1764
+ // the fragment in advance.
1765
+ //
1766
+ // The options object can contain `trigger: true` if you wish to have the
1767
+ // route callback be fired (not usually desirable), or `replace: true`, if
1768
+ // you wish to modify the current URL without adding an entry to the history.
1769
+ navigate: function(fragment, options) {
1770
+ if (!History.started) return false;
1771
+ if (!options || options === true) options = {trigger: !!options};
1772
+
1773
+ // Normalize the fragment.
1774
+ fragment = this.getFragment(fragment || '');
1775
+
1776
+ // Don't include a trailing slash on the root.
1777
+ var root = this.root;
1778
+ if (fragment === '' || fragment.charAt(0) === '?') {
1779
+ root = root.slice(0, -1) || '/';
1780
+ }
1781
+ var url = root + fragment;
1782
+
1783
+ // Strip the hash and decode for matching.
1784
+ fragment = this.decodeFragment(fragment.replace(pathStripper, ''));
1785
+
1786
+ if (this.fragment === fragment) return;
1787
+ this.fragment = fragment;
1788
+
1789
+ // If pushState is available, we use it to set the fragment as a real URL.
1790
+ if (this._usePushState) {
1791
+ this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
1792
+
1793
+ // If hash changes haven't been explicitly disabled, update the hash
1794
+ // fragment to store history.
1795
+ } else if (this._wantsHashChange) {
1796
+ this._updateHash(this.location, fragment, options.replace);
1797
+ if (this.iframe && (fragment !== this.getHash(this.iframe))) {
1798
+ // Opening and closing the iframe tricks IE7 and earlier to push a
1799
+ // history entry on hash-tag change. When replace is true, we don't
1800
+ // want this.
1801
+ if (!options.replace) this.iframe.document.open().close();
1802
+ this._updateHash(this.iframe.location, fragment, options.replace);
1803
+ }
1804
+
1805
+ // If you've told us that you explicitly don't want fallback hashchange-
1806
+ // based history, then `navigate` becomes a page refresh.
1807
+ } else {
1808
+ return this.location.assign(url);
1809
+ }
1810
+ if (options.trigger) return this.loadUrl(fragment);
1811
+ },
1812
+
1813
+ // Update the hash location, either replacing the current entry, or adding
1814
+ // a new one to the browser history.
1815
+ _updateHash: function(location, fragment, replace) {
1816
+ if (replace) {
1817
+ var href = location.href.replace(/(javascript:|#).*$/, '');
1818
+ location.replace(href + '#' + fragment);
1819
+ } else {
1820
+ // Some browsers require that `hash` contains a leading #.
1821
+ location.hash = '#' + fragment;
1822
+ }
1823
+ }
1824
+
1825
+ });
1826
+
1827
+ // Create the default Backbone.history.
1828
+ Backbone.history = new History;
1829
+
1830
+ // Helpers
1831
+ // -------
1832
+
1833
+ // Helper function to correctly set up the prototype chain for subclasses.
1834
+ // Similar to `goog.inherits`, but uses a hash of prototype properties and
1835
+ // class properties to be extended.
1836
+ var extend = function(protoProps, staticProps) {
1837
+ var parent = this;
1838
+ var child;
1839
+
1840
+ // The constructor function for the new subclass is either defined by you
1841
+ // (the "constructor" property in your `extend` definition), or defaulted
1842
+ // by us to simply call the parent constructor.
1843
+ if (protoProps && _.has(protoProps, 'constructor')) {
1844
+ child = protoProps.constructor;
1845
+ } else {
1846
+ child = function(){ return parent.apply(this, arguments); };
1847
+ }
1848
+
1849
+ // Add static properties to the constructor function, if supplied.
1850
+ _.extend(child, parent, staticProps);
1851
+
1852
+ // Set the prototype chain to inherit from `parent`, without calling
1853
+ // `parent` constructor function.
1854
+ var Surrogate = function(){ this.constructor = child; };
1855
+ Surrogate.prototype = parent.prototype;
1856
+ child.prototype = new Surrogate;
1857
+
1858
+ // Add prototype properties (instance properties) to the subclass,
1859
+ // if supplied.
1860
+ if (protoProps) _.extend(child.prototype, protoProps);
1861
+
1862
+ // Set a convenience property in case the parent's prototype is needed
1863
+ // later.
1864
+ child.__super__ = parent.prototype;
1865
+
1866
+ return child;
1867
+ };
1868
+
1869
+ // Set up inheritance for the model, collection, router, view and history.
1870
+ Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
1871
+
1872
+ // Throw an error when a URL is needed, and none is supplied.
1873
+ var urlError = function() {
1874
+ throw new Error('A "url" property or function must be specified');
1875
+ };
1876
+
1877
+ // Wrap an optional error callback with a fallback error event.
1878
+ var wrapError = function(model, options) {
1879
+ var error = options.error;
1880
+ options.error = function(resp) {
1881
+ if (error) error.call(options.context, model, resp, options);
1882
+ model.trigger('error', model, resp, options);
1883
+ };
1884
+ };
1885
+
1886
+ return Backbone;
1887
+
1888
+ }));