transit 0.0.1 → 0.0.2

Sign up to get free protection for your applications and to get access to all the features.
Files changed (186) hide show
  1. data/Gemfile +19 -11
  2. data/app/assets/images/transit/icon24x24.png +0 -0
  3. data/app/assets/images/transit/icon24x24_files.png +0 -0
  4. data/app/assets/images/transit/jplayer.swf +0 -0
  5. data/app/assets/images/transit/uploadify.swf +0 -0
  6. data/app/assets/images/transit/video_player.swf +0 -0
  7. data/app/assets/javascripts/jqtools/expose.js +224 -0
  8. data/app/assets/javascripts/jqtools/flashembed.js +300 -0
  9. data/app/assets/javascripts/jqtools/overlay.js +294 -0
  10. data/app/assets/javascripts/jqtools/scrollable.js +3 -0
  11. data/app/assets/javascripts/jqtools/scrollable/autoscroll.js +81 -0
  12. data/app/assets/javascripts/jqtools/scrollable/base.js +335 -0
  13. data/app/assets/javascripts/jqtools/scrollable/navigator.js +139 -0
  14. data/app/assets/javascripts/jqtools/validator.js +590 -0
  15. data/app/assets/javascripts/jqueryui/accordion.js +611 -0
  16. data/app/assets/javascripts/jqueryui/autocomplete.js +612 -0
  17. data/app/assets/javascripts/jqueryui/button.js +388 -0
  18. data/app/assets/javascripts/jqueryui/core.js +312 -0
  19. data/app/assets/javascripts/jqueryui/datepicker.js +1791 -0
  20. data/app/assets/javascripts/jqueryui/dialog.js +878 -0
  21. data/app/assets/javascripts/jqueryui/draggable.js +815 -0
  22. data/app/assets/javascripts/jqueryui/droppable.js +285 -0
  23. data/app/assets/javascripts/jqueryui/effects/blind.js +49 -0
  24. data/app/assets/javascripts/jqueryui/effects/bounce.js +78 -0
  25. data/app/assets/javascripts/jqueryui/effects/clip.js +54 -0
  26. data/app/assets/javascripts/jqueryui/effects/core.js +746 -0
  27. data/app/assets/javascripts/jqueryui/effects/drop.js +50 -0
  28. data/app/assets/javascripts/jqueryui/effects/explode.js +79 -0
  29. data/app/assets/javascripts/jqueryui/effects/fade.js +32 -0
  30. data/app/assets/javascripts/jqueryui/effects/fold.js +56 -0
  31. data/app/assets/javascripts/jqueryui/effects/highlight.js +50 -0
  32. data/app/assets/javascripts/jqueryui/effects/pulsate.js +51 -0
  33. data/app/assets/javascripts/jqueryui/effects/scale.js +178 -0
  34. data/app/assets/javascripts/jqueryui/effects/shake.js +57 -0
  35. data/app/assets/javascripts/jqueryui/effects/slide.js +50 -0
  36. data/app/assets/javascripts/jqueryui/effects/transfer.js +45 -0
  37. data/app/assets/javascripts/jqueryui/mouse.js +160 -0
  38. data/app/assets/javascripts/jqueryui/position.js +252 -0
  39. data/app/assets/javascripts/jqueryui/progressbar.js +109 -0
  40. data/app/assets/javascripts/jqueryui/resizable.js +814 -0
  41. data/app/assets/javascripts/jqueryui/selectable.js +266 -0
  42. data/app/assets/javascripts/jqueryui/slider.js +666 -0
  43. data/app/assets/javascripts/jqueryui/sortable.js +1077 -0
  44. data/app/assets/javascripts/jqueryui/tabs.js +758 -0
  45. data/app/assets/javascripts/jqueryui/widget.js +262 -0
  46. data/app/assets/javascripts/libs/backbone.js +1152 -0
  47. data/app/assets/javascripts/libs/cookie.js +89 -0
  48. data/app/assets/javascripts/libs/fileinput.js +130 -0
  49. data/app/assets/javascripts/libs/jplayer.js +1768 -0
  50. data/app/assets/javascripts/libs/proper.js +541 -0
  51. data/app/assets/javascripts/libs/sanitize.js +282 -0
  52. data/app/assets/javascripts/libs/selecttolist.js +75 -0
  53. data/app/assets/javascripts/libs/underscore.js +807 -0
  54. data/app/assets/javascripts/libs/uploadify.js +677 -0
  55. data/app/assets/javascripts/libs/wymeditor.js +9538 -0
  56. data/app/assets/javascripts/transit.js +4 -0
  57. data/app/assets/javascripts/transit/admin.js +22 -0
  58. data/app/assets/javascripts/transit/admin/contexts.js +52 -0
  59. data/app/assets/javascripts/transit/admin/fields.js +36 -0
  60. data/app/assets/javascripts/transit/admin/upload.js +109 -0
  61. data/app/assets/javascripts/transit/config.js.erb +101 -0
  62. data/app/assets/javascripts/transit/contexts/audio.js +39 -0
  63. data/app/assets/javascripts/transit/contexts/video.js +79 -0
  64. data/app/assets/javascripts/transit/core.js +171 -0
  65. data/app/assets/javascripts/transit/frontend.js +3 -0
  66. data/app/assets/javascripts/transit/lib/base64.js +120 -0
  67. data/app/assets/javascripts/transit/lib/editor.js +177 -0
  68. data/app/assets/javascripts/transit/views/audio_player.jst +22 -0
  69. data/app/assets/javascripts/transit/views/editor_toolbar.jst +12 -0
  70. data/app/assets/javascripts/transit/views/file_upload.jst +5 -0
  71. data/app/assets/javascripts/transit/views/video_player.jst +20 -0
  72. data/app/assets/javascripts/transit/views/wym_box.jst +4 -0
  73. data/app/assets/javascripts/transit/views/wym_iframe.jst +3 -0
  74. data/app/assets/stylesheets/transit.css.scss.erb +42 -0
  75. data/app/assets/stylesheets/transit/forms.css.scss +66 -0
  76. data/app/assets/stylesheets/transit/media/audio.css.scss +65 -0
  77. data/app/assets/stylesheets/transit/media/video.css.scss +30 -0
  78. data/app/assets/stylesheets/transit/panel.css.scss +100 -0
  79. data/app/assets/stylesheets/transit/ui.css.scss +507 -0
  80. data/app/controllers/pages_controller.rb +3 -0
  81. data/app/controllers/posts_controller.rb +3 -0
  82. data/app/controllers/transit/assets_controller.rb +38 -0
  83. data/app/controllers/transit/contexts_controller.rb +12 -9
  84. data/app/controllers/transit/pages_controller.rb +26 -0
  85. data/app/controllers/transit/posts_controller.rb +31 -0
  86. data/app/controllers/transit/topics_controller.rb +5 -0
  87. data/app/controllers/transit_controller.rb +16 -0
  88. data/app/helpers/transit/admin_helper.rb +43 -0
  89. data/app/helpers/transit/form_helper.rb +17 -0
  90. data/app/helpers/transit/package_helper.rb +41 -0
  91. data/app/helpers/transit/pagination_helper.rb +58 -0
  92. data/app/helpers/transit_helper.rb +42 -0
  93. data/app/models/comment.rb +37 -0
  94. data/app/models/contexts/audio.rb +12 -0
  95. data/app/models/{text.rb → contexts/text.rb} +0 -0
  96. data/app/models/contexts/video.rb +24 -0
  97. data/app/models/topic.rb +19 -0
  98. data/app/models/transit/asset.rb +68 -0
  99. data/{lib → app/models}/transit/context.rb +29 -0
  100. data/app/views/contexts/_text.html.erb +1 -1
  101. data/app/views/posts/index.rss.builder +18 -0
  102. data/app/views/transit/assets/_file.html.erb +4 -0
  103. data/app/views/transit/assets/_image.html.erb +13 -0
  104. data/app/views/transit/assets/create.js.erb +8 -0
  105. data/app/views/transit/assets/destroy.js.erb +3 -0
  106. data/app/views/transit/assets/manage.html.erb +20 -0
  107. data/app/views/transit/contexts/_audio.html.erb +18 -0
  108. data/app/views/transit/contexts/_text.html.erb +6 -0
  109. data/app/views/transit/contexts/_video.html.erb +13 -0
  110. data/app/views/transit/contexts/destroy.js.erb +1 -0
  111. data/app/views/transit/contexts/index.html.erb +5 -0
  112. data/app/views/transit/contexts/new.js.erb +7 -0
  113. data/app/views/transit/contexts/show.html.erb +8 -0
  114. data/app/views/transit/index.html.erb +26 -0
  115. data/app/views/transit/index.js.erb +1 -0
  116. data/app/views/transit/interface/post_panel.html.erb +96 -0
  117. data/app/views/transit/pages/_table.html.erb +7 -0
  118. data/app/views/transit/pages/edit.html.erb +17 -0
  119. data/app/views/transit/pages/index.html.erb +17 -0
  120. data/app/views/transit/pages/update.js.erb +1 -0
  121. data/app/views/transit/posts/_form.html.erb +49 -0
  122. data/app/views/transit/posts/edit.html.erb +14 -0
  123. data/app/views/transit/posts/new.html.erb +21 -0
  124. data/app/views/transit/table.html.erb +13 -0
  125. data/app/views/transit/table.js.erb +8 -0
  126. data/app/views/transit/topics/manage.html.erb +28 -0
  127. data/config/locales/en.yml +22 -0
  128. data/config/routes.rb +3 -3
  129. data/lib/transit.rb +51 -17
  130. data/lib/transit/admin.rb +85 -0
  131. data/lib/transit/builders/form_builder.rb +319 -0
  132. data/lib/transit/builders/jst_builder.rb +38 -0
  133. data/lib/transit/builders/package_builder.rb +45 -0
  134. data/lib/transit/config.rb +20 -0
  135. data/lib/transit/controller/generator.rb +42 -0
  136. data/lib/transit/controller/responder.rb +34 -0
  137. data/lib/transit/core_ext.rb +18 -0
  138. data/lib/transit/errors/resource_not_found.rb +6 -0
  139. data/lib/transit/model/assets.rb +14 -0
  140. data/lib/transit/model/attachments.rb +55 -0
  141. data/lib/transit/model/auto_increment.rb +22 -0
  142. data/lib/transit/model/base.rb +56 -0
  143. data/lib/transit/model/comments.rb +19 -0
  144. data/lib/transit/model/hooks.rb +38 -0
  145. data/lib/transit/model/owners.rb +14 -0
  146. data/lib/transit/model/paginator.rb +92 -0
  147. data/lib/transit/model/topics.rb +14 -0
  148. data/lib/transit/package/page.rb +20 -12
  149. data/lib/transit/package/post.rb +87 -33
  150. data/lib/transit/package/post/validations.rb +14 -0
  151. data/lib/transit/rails/engine.rb +29 -13
  152. data/lib/transit/rails/railtie.rb +31 -0
  153. data/lib/transit/rails/routing.rb +11 -6
  154. data/lib/transit/services.rb +13 -0
  155. data/lib/transit/services/base.rb +14 -0
  156. data/lib/transit/services/facebook.rb +13 -0
  157. data/lib/transit/services/ted.rb +10 -0
  158. data/lib/transit/services/twitter.rb +13 -0
  159. data/lib/transit/services/vimeo.rb +10 -0
  160. data/lib/transit/services/you_tube.rb +12 -0
  161. data/lib/transit/version.rb +1 -1
  162. metadata +178 -31
  163. data/app/assets/stylesheets/includes/_compat.scss +0 -24
  164. data/app/assets/stylesheets/includes/_defaults.scss +0 -99
  165. data/app/assets/stylesheets/includes/_global.scss +0 -16
  166. data/app/assets/stylesheets/includes/_imports.scss +0 -27
  167. data/app/assets/stylesheets/includes/_mixins.scss +0 -38
  168. data/app/assets/stylesheets/includes/_setup.scss +0 -85
  169. data/app/assets/stylesheets/layout.css.scss +0 -29
  170. data/app/assets/stylesheets/transit.css +0 -3
  171. data/app/controllers/application_controller.rb +0 -5
  172. data/app/controllers/transit/index_controller.rb +0 -7
  173. data/app/controllers/transit/packages_controller.rb +0 -64
  174. data/app/controllers/transit/transit_controller.rb +0 -4
  175. data/app/helpers/routing_helpers.rb +0 -7
  176. data/app/models/audio.rb +0 -4
  177. data/app/models/package_asset.rb +0 -11
  178. data/app/models/video.rb +0 -8
  179. data/app/views/contexts/_audio.html.erb +0 -1
  180. data/app/views/contexts/_video.html.erb +0 -1
  181. data/app/views/layouts/transit.html.erb +0 -31
  182. data/app/views/transit/index/index.html.erb +0 -0
  183. data/lib/transit/helpers/controller_helpers.rb +0 -40
  184. data/lib/transit/helpers/model_helpers.rb +0 -26
  185. data/lib/transit/package.rb +0 -25
  186. data/lib/transit/package/base.rb +0 -49
@@ -0,0 +1,262 @@
1
+ /*!
2
+ * jQuery UI Widget 1.8.13
3
+ *
4
+ * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
5
+ * Dual licensed under the MIT or GPL Version 2 licenses.
6
+ * http://jquery.org/license
7
+ *
8
+ * http://docs.jquery.com/UI/Widget
9
+ */
10
+ (function( $, undefined ) {
11
+
12
+ // jQuery 1.4+
13
+ if ( $.cleanData ) {
14
+ var _cleanData = $.cleanData;
15
+ $.cleanData = function( elems ) {
16
+ for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
17
+ $( elem ).triggerHandler( "remove" );
18
+ }
19
+ _cleanData( elems );
20
+ };
21
+ } else {
22
+ var _remove = $.fn.remove;
23
+ $.fn.remove = function( selector, keepData ) {
24
+ return this.each(function() {
25
+ if ( !keepData ) {
26
+ if ( !selector || $.filter( selector, [ this ] ).length ) {
27
+ $( "*", this ).add( [ this ] ).each(function() {
28
+ $( this ).triggerHandler( "remove" );
29
+ });
30
+ }
31
+ }
32
+ return _remove.call( $(this), selector, keepData );
33
+ });
34
+ };
35
+ }
36
+
37
+ $.widget = function( name, base, prototype ) {
38
+ var namespace = name.split( "." )[ 0 ],
39
+ fullName;
40
+ name = name.split( "." )[ 1 ];
41
+ fullName = namespace + "-" + name;
42
+
43
+ if ( !prototype ) {
44
+ prototype = base;
45
+ base = $.Widget;
46
+ }
47
+
48
+ // create selector for plugin
49
+ $.expr[ ":" ][ fullName ] = function( elem ) {
50
+ return !!$.data( elem, name );
51
+ };
52
+
53
+ $[ namespace ] = $[ namespace ] || {};
54
+ $[ namespace ][ name ] = function( options, element ) {
55
+ // allow instantiation without initializing for simple inheritance
56
+ if ( arguments.length ) {
57
+ this._createWidget( options, element );
58
+ }
59
+ };
60
+
61
+ var basePrototype = new base();
62
+ // we need to make the options hash a property directly on the new instance
63
+ // otherwise we'll modify the options hash on the prototype that we're
64
+ // inheriting from
65
+ // $.each( basePrototype, function( key, val ) {
66
+ // if ( $.isPlainObject(val) ) {
67
+ // basePrototype[ key ] = $.extend( {}, val );
68
+ // }
69
+ // });
70
+ basePrototype.options = $.extend( true, {}, basePrototype.options );
71
+ $[ namespace ][ name ].prototype = $.extend( true, basePrototype, {
72
+ namespace: namespace,
73
+ widgetName: name,
74
+ widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name,
75
+ widgetBaseClass: fullName
76
+ }, prototype );
77
+
78
+ $.widget.bridge( name, $[ namespace ][ name ] );
79
+ };
80
+
81
+ $.widget.bridge = function( name, object ) {
82
+ $.fn[ name ] = function( options ) {
83
+ var isMethodCall = typeof options === "string",
84
+ args = Array.prototype.slice.call( arguments, 1 ),
85
+ returnValue = this;
86
+
87
+ // allow multiple hashes to be passed on init
88
+ options = !isMethodCall && args.length ?
89
+ $.extend.apply( null, [ true, options ].concat(args) ) :
90
+ options;
91
+
92
+ // prevent calls to internal methods
93
+ if ( isMethodCall && options.charAt( 0 ) === "_" ) {
94
+ return returnValue;
95
+ }
96
+
97
+ if ( isMethodCall ) {
98
+ this.each(function() {
99
+ var instance = $.data( this, name ),
100
+ methodValue = instance && $.isFunction( instance[options] ) ?
101
+ instance[ options ].apply( instance, args ) :
102
+ instance;
103
+ // TODO: add this back in 1.9 and use $.error() (see #5972)
104
+ // if ( !instance ) {
105
+ // throw "cannot call methods on " + name + " prior to initialization; " +
106
+ // "attempted to call method '" + options + "'";
107
+ // }
108
+ // if ( !$.isFunction( instance[options] ) ) {
109
+ // throw "no such method '" + options + "' for " + name + " widget instance";
110
+ // }
111
+ // var methodValue = instance[ options ].apply( instance, args );
112
+ if ( methodValue !== instance && methodValue !== undefined ) {
113
+ returnValue = methodValue;
114
+ return false;
115
+ }
116
+ });
117
+ } else {
118
+ this.each(function() {
119
+ var instance = $.data( this, name );
120
+ if ( instance ) {
121
+ instance.option( options || {} )._init();
122
+ } else {
123
+ $.data( this, name, new object( options, this ) );
124
+ }
125
+ });
126
+ }
127
+
128
+ return returnValue;
129
+ };
130
+ };
131
+
132
+ $.Widget = function( options, element ) {
133
+ // allow instantiation without initializing for simple inheritance
134
+ if ( arguments.length ) {
135
+ this._createWidget( options, element );
136
+ }
137
+ };
138
+
139
+ $.Widget.prototype = {
140
+ widgetName: "widget",
141
+ widgetEventPrefix: "",
142
+ options: {
143
+ disabled: false
144
+ },
145
+ _createWidget: function( options, element ) {
146
+ // $.widget.bridge stores the plugin instance, but we do it anyway
147
+ // so that it's stored even before the _create function runs
148
+ $.data( element, this.widgetName, this );
149
+ this.element = $( element );
150
+ this.options = $.extend( true, {},
151
+ this.options,
152
+ this._getCreateOptions(),
153
+ options );
154
+
155
+ var self = this;
156
+ this.element.bind( "remove." + this.widgetName, function() {
157
+ self.destroy();
158
+ });
159
+
160
+ this._create();
161
+ this._trigger( "create" );
162
+ this._init();
163
+ },
164
+ _getCreateOptions: function() {
165
+ return $.metadata && $.metadata.get( this.element[0] )[ this.widgetName ];
166
+ },
167
+ _create: function() {},
168
+ _init: function() {},
169
+
170
+ destroy: function() {
171
+ this.element
172
+ .unbind( "." + this.widgetName )
173
+ .removeData( this.widgetName );
174
+ this.widget()
175
+ .unbind( "." + this.widgetName )
176
+ .removeAttr( "aria-disabled" )
177
+ .removeClass(
178
+ this.widgetBaseClass + "-disabled " +
179
+ "ui-state-disabled" );
180
+ },
181
+
182
+ widget: function() {
183
+ return this.element;
184
+ },
185
+
186
+ option: function( key, value ) {
187
+ var options = key;
188
+
189
+ if ( arguments.length === 0 ) {
190
+ // don't return a reference to the internal hash
191
+ return $.extend( {}, this.options );
192
+ }
193
+
194
+ if (typeof key === "string" ) {
195
+ if ( value === undefined ) {
196
+ return this.options[ key ];
197
+ }
198
+ options = {};
199
+ options[ key ] = value;
200
+ }
201
+
202
+ this._setOptions( options );
203
+
204
+ return this;
205
+ },
206
+ _setOptions: function( options ) {
207
+ var self = this;
208
+ $.each( options, function( key, value ) {
209
+ self._setOption( key, value );
210
+ });
211
+
212
+ return this;
213
+ },
214
+ _setOption: function( key, value ) {
215
+ this.options[ key ] = value;
216
+
217
+ if ( key === "disabled" ) {
218
+ this.widget()
219
+ [ value ? "addClass" : "removeClass"](
220
+ this.widgetBaseClass + "-disabled" + " " +
221
+ "ui-state-disabled" )
222
+ .attr( "aria-disabled", value );
223
+ }
224
+
225
+ return this;
226
+ },
227
+
228
+ enable: function() {
229
+ return this._setOption( "disabled", false );
230
+ },
231
+ disable: function() {
232
+ return this._setOption( "disabled", true );
233
+ },
234
+
235
+ _trigger: function( type, event, data ) {
236
+ var callback = this.options[ type ];
237
+
238
+ event = $.Event( event );
239
+ event.type = ( type === this.widgetEventPrefix ?
240
+ type :
241
+ this.widgetEventPrefix + type ).toLowerCase();
242
+ data = data || {};
243
+
244
+ // copy original event properties over to the new event
245
+ // this would happen if we could call $.event.fix instead of $.Event
246
+ // but we don't have a way to force an event to be fixed multiple times
247
+ if ( event.originalEvent ) {
248
+ for ( var i = $.event.props.length, prop; i; ) {
249
+ prop = $.event.props[ --i ];
250
+ event[ prop ] = event.originalEvent[ prop ];
251
+ }
252
+ }
253
+
254
+ this.element.trigger( event, data );
255
+
256
+ return !( $.isFunction(callback) &&
257
+ callback.call( this.element[0], event, data ) === false ||
258
+ event.isDefaultPrevented() );
259
+ }
260
+ };
261
+
262
+ })( jQuery );
@@ -0,0 +1,1152 @@
1
+ // Backbone.js 0.5.0-pre
2
+ // (c) 2010 Jeremy Ashkenas, DocumentCloud Inc.
3
+ // Backbone may be freely distributed under the MIT license.
4
+ // For all details and documentation:
5
+ // http://documentcloud.github.com/backbone
6
+
7
+ (function(){
8
+
9
+ // Initial Setup
10
+ // -------------
11
+
12
+ // Save a reference to the global object.
13
+ var root = this;
14
+
15
+ // Save the previous value of the `Backbone` variable.
16
+ var previousBackbone = root.Backbone;
17
+
18
+ // The top-level namespace. All public Backbone classes and modules will
19
+ // be attached to this. Exported for both CommonJS and the browser.
20
+ var Backbone;
21
+ if (typeof exports !== 'undefined') {
22
+ Backbone = exports;
23
+ } else {
24
+ Backbone = root.Backbone = {};
25
+ }
26
+
27
+ // Current version of the library. Keep in sync with `package.json`.
28
+ Backbone.VERSION = '0.5.0-pre';
29
+
30
+ // Require Underscore, if we're on the server, and it's not already present.
31
+ var _ = root._;
32
+ if (!_ && (typeof require !== 'undefined')) _ = require('underscore')._;
33
+
34
+ // For Backbone's purposes, jQuery or Zepto owns the `$` variable.
35
+ var $ = root.jQuery || root.Zepto;
36
+
37
+ // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
38
+ // to its previous owner. Returns a reference to this Backbone object.
39
+ Backbone.noConflict = function() {
40
+ root.Backbone = previousBackbone;
41
+ return this;
42
+ };
43
+
44
+ // Turn on `emulateHTTP` to use support legacy HTTP servers. Setting this option will
45
+ // fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and set a
46
+ // `X-Http-Method-Override` header.
47
+ Backbone.emulateHTTP = false;
48
+
49
+ // Turn on `emulateJSON` to support legacy servers that can't deal with direct
50
+ // `application/json` requests ... will encode the body as
51
+ // `application/x-www-form-urlencoded` instead and will send the model in a
52
+ // form param named `model`.
53
+ Backbone.emulateJSON = false;
54
+
55
+ // Backbone.Events
56
+ // -----------------
57
+
58
+ // A module that can be mixed in to *any object* in order to provide it with
59
+ // custom events. You may `bind` or `unbind` a callback function to an event;
60
+ // `trigger`-ing an event fires all callbacks in succession.
61
+ //
62
+ // var object = {};
63
+ // _.extend(object, Backbone.Events);
64
+ // object.bind('expand', function(){ alert('expanded'); });
65
+ // object.trigger('expand');
66
+ //
67
+ Backbone.Events = {
68
+
69
+ // Bind an event, specified by a string name, `ev`, to a `callback` function.
70
+ // Passing `"all"` will bind the callback to all events fired.
71
+ bind : function(ev, callback) {
72
+ var calls = this._callbacks || (this._callbacks = {});
73
+ var list = calls[ev] || (calls[ev] = []);
74
+ list.push(callback);
75
+ return this;
76
+ },
77
+
78
+ // Remove one or many callbacks. If `callback` is null, removes all
79
+ // callbacks for the event. If `ev` is null, removes all bound callbacks
80
+ // for all events.
81
+ unbind : function(ev, callback) {
82
+ var calls;
83
+ if (!ev) {
84
+ this._callbacks = {};
85
+ } else if (calls = this._callbacks) {
86
+ if (!callback) {
87
+ calls[ev] = [];
88
+ } else {
89
+ var list = calls[ev];
90
+ if (!list) return this;
91
+ for (var i = 0, l = list.length; i < l; i++) {
92
+ if (callback === list[i]) {
93
+ list[i] = null;
94
+ break;
95
+ }
96
+ }
97
+ }
98
+ }
99
+ return this;
100
+ },
101
+
102
+ // Trigger an event, firing all bound callbacks. Callbacks are passed the
103
+ // same arguments as `trigger` is, apart from the event name.
104
+ // Listening for `"all"` passes the true event name as the first argument.
105
+ trigger : function(eventName) {
106
+ var list, calls, ev, callback, args;
107
+ var both = 2;
108
+ if (!(calls = this._callbacks)) return this;
109
+ while (both--) {
110
+ ev = both ? eventName : 'all';
111
+ if (list = calls[ev]) {
112
+ for (var i = 0, l = list.length; i < l; i++) {
113
+ if (!(callback = list[i])) {
114
+ list.splice(i, 1); i--; l--;
115
+ } else {
116
+ args = both ? Array.prototype.slice.call(arguments, 1) : arguments;
117
+ callback.apply(this, args);
118
+ }
119
+ }
120
+ }
121
+ }
122
+ return this;
123
+ }
124
+
125
+ };
126
+
127
+ // Backbone.Model
128
+ // --------------
129
+
130
+ // Create a new model, with defined attributes. A client id (`cid`)
131
+ // is automatically generated and assigned for you.
132
+ Backbone.Model = function(attributes, options) {
133
+ var defaults;
134
+ attributes || (attributes = {});
135
+ if (defaults = this.defaults) {
136
+ if (_.isFunction(defaults)) defaults = defaults();
137
+ attributes = _.extend({}, defaults, attributes);
138
+ }
139
+ this.attributes = {};
140
+ this._escapedAttributes = {};
141
+ this.cid = _.uniqueId('c');
142
+ this.set(attributes, {silent : true});
143
+ this._changed = false;
144
+ this._previousAttributes = _.clone(this.attributes);
145
+ if (options && options.collection) this.collection = options.collection;
146
+ this.initialize(attributes, options);
147
+ };
148
+
149
+ // Attach all inheritable methods to the Model prototype.
150
+ _.extend(Backbone.Model.prototype, Backbone.Events, {
151
+
152
+ // A snapshot of the model's previous attributes, taken immediately
153
+ // after the last `"change"` event was fired.
154
+ _previousAttributes : null,
155
+
156
+ // Has the item been changed since the last `"change"` event?
157
+ _changed : false,
158
+
159
+ // The default name for the JSON `id` attribute is `"id"`. MongoDB and
160
+ // CouchDB users may want to set this to `"_id"`.
161
+ idAttribute : 'id',
162
+
163
+ // Initialize is an empty function by default. Override it with your own
164
+ // initialization logic.
165
+ initialize : function(){},
166
+
167
+ // Return a copy of the model's `attributes` object.
168
+ toJSON : function() {
169
+ return _.clone(this.attributes);
170
+ },
171
+
172
+ // Get the value of an attribute.
173
+ get : function(attr) {
174
+ return this.attributes[attr];
175
+ },
176
+
177
+ // Get the HTML-escaped value of an attribute.
178
+ escape : function(attr) {
179
+ var html;
180
+ if (html = this._escapedAttributes[attr]) return html;
181
+ var val = this.attributes[attr];
182
+ return this._escapedAttributes[attr] = escapeHTML(val == null ? '' : '' + val);
183
+ },
184
+
185
+ // Returns `true` if the attribute contains a value that is not null
186
+ // or undefined.
187
+ has : function(attr) {
188
+ return this.attributes[attr] != null;
189
+ },
190
+
191
+ // Set a hash of model attributes on the object, firing `"change"` unless you
192
+ // choose to silence it.
193
+ set : function(attrs, options) {
194
+
195
+ // Extract attributes and options.
196
+ options || (options = {});
197
+ if (!attrs) return this;
198
+ if (attrs.attributes) attrs = attrs.attributes;
199
+ var now = this.attributes, escaped = this._escapedAttributes;
200
+
201
+ // Run validation.
202
+ if (!options.silent && this.validate && !this._performValidation(attrs, options)) return false;
203
+
204
+ // Check for changes of `id`.
205
+ if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
206
+
207
+ // We're about to start triggering change events.
208
+ var alreadyChanging = this._changing;
209
+ this._changing = true;
210
+
211
+ // Update attributes.
212
+ for (var attr in attrs) {
213
+ var val = attrs[attr];
214
+ if (!_.isEqual(now[attr], val)) {
215
+ now[attr] = val;
216
+ delete escaped[attr];
217
+ this._changed = true;
218
+ if (!options.silent) this.trigger('change:' + attr, this, val, options);
219
+ }
220
+ }
221
+
222
+ // Fire the `"change"` event, if the model has been changed.
223
+ if (!alreadyChanging && !options.silent && this._changed) this.change(options);
224
+ this._changing = false;
225
+ return this;
226
+ },
227
+
228
+ // Remove an attribute from the model, firing `"change"` unless you choose
229
+ // to silence it. `unset` is a noop if the attribute doesn't exist.
230
+ unset : function(attr, options) {
231
+ if (!(attr in this.attributes)) return this;
232
+ options || (options = {});
233
+ var value = this.attributes[attr];
234
+
235
+ // Run validation.
236
+ var validObj = {};
237
+ validObj[attr] = void 0;
238
+ if (!options.silent && this.validate && !this._performValidation(validObj, options)) return false;
239
+
240
+ // Remove the attribute.
241
+ delete this.attributes[attr];
242
+ delete this._escapedAttributes[attr];
243
+ if (attr == this.idAttribute) delete this.id;
244
+ this._changed = true;
245
+ if (!options.silent) {
246
+ this.trigger('change:' + attr, this, void 0, options);
247
+ this.change(options);
248
+ }
249
+ return this;
250
+ },
251
+
252
+ // Clear all attributes on the model, firing `"change"` unless you choose
253
+ // to silence it.
254
+ clear : function(options) {
255
+ options || (options = {});
256
+ var old = this.attributes;
257
+
258
+ // Run validation.
259
+ var validObj = {};
260
+ for (var attr in old) validObj[attr] = void 0;
261
+ if (!options.silent && this.validate && !this._performValidation(validObj, options)) return false;
262
+
263
+ this.attributes = {};
264
+ this._escapedAttributes = {};
265
+ this._changed = true;
266
+ if (!options.silent) {
267
+ for (var attr in old) {
268
+ this.trigger('change:' + attr, this, void 0, options);
269
+ }
270
+ this.change(options);
271
+ }
272
+ return this;
273
+ },
274
+
275
+ // Fetch the model from the server. If the server's representation of the
276
+ // model differs from its current attributes, they will be overriden,
277
+ // triggering a `"change"` event.
278
+ fetch : function(options) {
279
+ options || (options = {});
280
+ var model = this;
281
+ var success = options.success;
282
+ options.success = function(resp, status, xhr) {
283
+ if (!model.set(model.parse(resp, xhr), options)) return false;
284
+ if (success) success(model, resp);
285
+ };
286
+ options.error = wrapError(options.error, model, options);
287
+ return (this.sync || Backbone.sync).call(this, 'read', this, options);
288
+ },
289
+
290
+ // Set a hash of model attributes, and sync the model to the server.
291
+ // If the server returns an attributes hash that differs, the model's
292
+ // state will be `set` again.
293
+ save : function(attrs, options) {
294
+ options || (options = {});
295
+ if (attrs && !this.set(attrs, options)) return false;
296
+ var model = this;
297
+ var success = options.success;
298
+ options.success = function(resp, status, xhr) {
299
+ if (!model.set(model.parse(resp, xhr), options)) return false;
300
+ if (success) success(model, resp, xhr);
301
+ };
302
+ options.error = wrapError(options.error, model, options);
303
+ var method = this.isNew() ? 'create' : 'update';
304
+ return (this.sync || Backbone.sync).call(this, method, this, options);
305
+ },
306
+
307
+ // Destroy this model on the server if it was already persisted. Upon success, the model is removed
308
+ // from its collection, if it has one.
309
+ destroy : function(options) {
310
+ options || (options = {});
311
+ if (this.isNew()) return this.trigger('destroy', this, this.collection, options);
312
+ var model = this;
313
+ var success = options.success;
314
+ options.success = function(resp) {
315
+ model.trigger('destroy', model, model.collection, options);
316
+ if (success) success(model, resp);
317
+ };
318
+ options.error = wrapError(options.error, model, options);
319
+ return (this.sync || Backbone.sync).call(this, 'delete', this, options);
320
+ },
321
+
322
+ // Default URL for the model's representation on the server -- if you're
323
+ // using Backbone's restful methods, override this to change the endpoint
324
+ // that will be called.
325
+ url : function() {
326
+ var base = getUrl(this.collection) || this.urlRoot || urlError();
327
+ if (this.isNew()) return base;
328
+ return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + encodeURIComponent(this.id);
329
+ },
330
+
331
+ // **parse** converts a response into the hash of attributes to be `set` on
332
+ // the model. The default implementation is just to pass the response along.
333
+ parse : function(resp, xhr) {
334
+ return resp;
335
+ },
336
+
337
+ // Create a new model with identical attributes to this one.
338
+ clone : function() {
339
+ return new this.constructor(this);
340
+ },
341
+
342
+ // A model is new if it has never been saved to the server, and has a negative
343
+ // ID.
344
+ isNew : function() {
345
+ return !this.id;
346
+ },
347
+
348
+ // Call this method to manually fire a `change` event for this model.
349
+ // Calling this will cause all objects observing the model to update.
350
+ change : function(options) {
351
+ this.trigger('change', this, options);
352
+ this._previousAttributes = _.clone(this.attributes);
353
+ this._changed = false;
354
+ },
355
+
356
+ // Determine if the model has changed since the last `"change"` event.
357
+ // If you specify an attribute name, determine if that attribute has changed.
358
+ hasChanged : function(attr) {
359
+ if (attr) return this._previousAttributes[attr] != this.attributes[attr];
360
+ return this._changed;
361
+ },
362
+
363
+ // Return an object containing all the attributes that have changed, or false
364
+ // if there are no changed attributes. Useful for determining what parts of a
365
+ // view need to be updated and/or what attributes need to be persisted to
366
+ // the server.
367
+ changedAttributes : function(now) {
368
+ now || (now = this.attributes);
369
+ var old = this._previousAttributes;
370
+ var changed = false;
371
+ for (var attr in now) {
372
+ if (!_.isEqual(old[attr], now[attr])) {
373
+ changed = changed || {};
374
+ changed[attr] = now[attr];
375
+ }
376
+ }
377
+ return changed;
378
+ },
379
+
380
+ // Get the previous value of an attribute, recorded at the time the last
381
+ // `"change"` event was fired.
382
+ previous : function(attr) {
383
+ if (!attr || !this._previousAttributes) return null;
384
+ return this._previousAttributes[attr];
385
+ },
386
+
387
+ // Get all of the attributes of the model at the time of the previous
388
+ // `"change"` event.
389
+ previousAttributes : function() {
390
+ return _.clone(this._previousAttributes);
391
+ },
392
+
393
+ // Run validation against a set of incoming attributes, returning `true`
394
+ // if all is well. If a specific `error` callback has been passed,
395
+ // call that instead of firing the general `"error"` event.
396
+ _performValidation : function(attrs, options) {
397
+ var error = this.validate(attrs);
398
+ if (error) {
399
+ if (options.error) {
400
+ options.error(this, error, options);
401
+ } else {
402
+ this.trigger('error', this, error, options);
403
+ }
404
+ return false;
405
+ }
406
+ return true;
407
+ }
408
+
409
+ });
410
+
411
+ // Backbone.Collection
412
+ // -------------------
413
+
414
+ // Provides a standard collection class for our sets of models, ordered
415
+ // or unordered. If a `comparator` is specified, the Collection will maintain
416
+ // its models in sort order, as they're added and removed.
417
+ Backbone.Collection = function(models, options) {
418
+ options || (options = {});
419
+ if (options.comparator) this.comparator = options.comparator;
420
+ _.bindAll(this, '_onModelEvent', '_removeReference');
421
+ this._reset();
422
+ if (models) this.reset(models, {silent: true});
423
+ this.initialize(models, options);
424
+ };
425
+
426
+ // Define the Collection's inheritable methods.
427
+ _.extend(Backbone.Collection.prototype, Backbone.Events, {
428
+
429
+ // The default model for a collection is just a **Backbone.Model**.
430
+ // This should be overridden in most cases.
431
+ model : Backbone.Model,
432
+
433
+ // Initialize is an empty function by default. Override it with your own
434
+ // initialization logic.
435
+ initialize : function(){},
436
+
437
+ // The JSON representation of a Collection is an array of the
438
+ // models' attributes.
439
+ toJSON : function() {
440
+ return this.map(function(model){ return model.toJSON(); });
441
+ },
442
+
443
+ // Add a model, or list of models to the set. Pass **silent** to avoid
444
+ // firing the `added` event for every new model.
445
+ add : function(models, options) {
446
+ if (_.isArray(models)) {
447
+ for (var i = 0, l = models.length; i < l; i++) {
448
+ this._add(models[i], options);
449
+ }
450
+ } else {
451
+ this._add(models, options);
452
+ }
453
+ return this;
454
+ },
455
+
456
+ // Remove a model, or a list of models from the set. Pass silent to avoid
457
+ // firing the `removed` event for every model removed.
458
+ remove : function(models, options) {
459
+ if (_.isArray(models)) {
460
+ for (var i = 0, l = models.length; i < l; i++) {
461
+ this._remove(models[i], options);
462
+ }
463
+ } else {
464
+ this._remove(models, options);
465
+ }
466
+ return this;
467
+ },
468
+
469
+ // Get a model from the set by id.
470
+ get : function(id) {
471
+ if (id == null) return null;
472
+ return this._byId[id.id != null ? id.id : id];
473
+ },
474
+
475
+ // Get a model from the set by client id.
476
+ getByCid : function(cid) {
477
+ return cid && this._byCid[cid.cid || cid];
478
+ },
479
+
480
+ // Get the model at the given index.
481
+ at: function(index) {
482
+ return this.models[index];
483
+ },
484
+
485
+ // Force the collection to re-sort itself. You don't need to call this under normal
486
+ // circumstances, as the set will maintain sort order as each item is added.
487
+ sort : function(options) {
488
+ options || (options = {});
489
+ if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
490
+ this.models = this.sortBy(this.comparator);
491
+ if (!options.silent) this.trigger('reset', this, options);
492
+ return this;
493
+ },
494
+
495
+ // Pluck an attribute from each model in the collection.
496
+ pluck : function(attr) {
497
+ return _.map(this.models, function(model){ return model.get(attr); });
498
+ },
499
+
500
+ // When you have more items than you want to add or remove individually,
501
+ // you can reset the entire set with a new list of models, without firing
502
+ // any `added` or `removed` events. Fires `reset` when finished.
503
+ reset : function(models, options) {
504
+ models || (models = []);
505
+ options || (options = {});
506
+ this.each(this._removeReference);
507
+ this._reset();
508
+ this.add(models, {silent: true});
509
+ if (!options.silent) this.trigger('reset', this, options);
510
+ return this;
511
+ },
512
+
513
+ // Fetch the default set of models for this collection, resetting the
514
+ // collection when they arrive. If `add: true` is passed, appends the
515
+ // models to the collection instead of resetting.
516
+ fetch : function(options) {
517
+ options || (options = {});
518
+ var collection = this;
519
+ var success = options.success;
520
+ options.success = function(resp, status, xhr) {
521
+ collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options);
522
+ if (success) success(collection, resp);
523
+ };
524
+ options.error = wrapError(options.error, collection, options);
525
+ return (this.sync || Backbone.sync).call(this, 'read', this, options);
526
+ },
527
+
528
+ // Create a new instance of a model in this collection. After the model
529
+ // has been created on the server, it will be added to the collection.
530
+ // Returns the model, or 'false' if validation on a new model fails.
531
+ create : function(model, options) {
532
+ var coll = this;
533
+ options || (options = {});
534
+ model = this._prepareModel(model, options);
535
+ if (!model) return false;
536
+ var success = options.success;
537
+ options.success = function(nextModel, resp, xhr) {
538
+ coll.add(nextModel, options);
539
+ if (success) success(nextModel, resp, xhr);
540
+ };
541
+ model.save(null, options);
542
+ return model;
543
+ },
544
+
545
+ // **parse** converts a response into a list of models to be added to the
546
+ // collection. The default implementation is just to pass it through.
547
+ parse : function(resp, xhr) {
548
+ return resp;
549
+ },
550
+
551
+ // Proxy to _'s chain. Can't be proxied the same way the rest of the
552
+ // underscore methods are proxied because it relies on the underscore
553
+ // constructor.
554
+ chain: function () {
555
+ return _(this.models).chain();
556
+ },
557
+
558
+ // Reset all internal state. Called when the collection is refreshed.
559
+ _reset : function(options) {
560
+ this.length = 0;
561
+ this.models = [];
562
+ this._byId = {};
563
+ this._byCid = {};
564
+ },
565
+
566
+ // Prepare a model to be added to this collection
567
+ _prepareModel: function(model, options) {
568
+ if (!(model instanceof Backbone.Model)) {
569
+ var attrs = model;
570
+ model = new this.model(null, {collection: this});
571
+ if (!model.set(attrs, options)) model = false;
572
+ } else if (!model.collection) {
573
+ model.collection = this;
574
+ }
575
+ return model;
576
+ },
577
+
578
+ // Internal implementation of adding a single model to the set, updating
579
+ // hash indexes for `id` and `cid` lookups.
580
+ // Returns the model, or 'false' if validation on a new model fails.
581
+ _add : function(model, options) {
582
+ options || (options = {});
583
+ model = this._prepareModel(model, options);
584
+ if (!model) return false;
585
+ var already = this.getByCid(model);
586
+ if (already) throw new Error(["Can't add the same model to a set twice", already.id]);
587
+ this._byId[model.id] = model;
588
+ this._byCid[model.cid] = model;
589
+ var index = options.at != null ? options.at :
590
+ this.comparator ? this.sortedIndex(model, this.comparator) :
591
+ this.length;
592
+ this.models.splice(index, 0, model);
593
+ model.bind('all', this._onModelEvent);
594
+ this.length++;
595
+ if (!options.silent) model.trigger('add', model, this, options);
596
+ return model;
597
+ },
598
+
599
+ // Internal implementation of removing a single model from the set, updating
600
+ // hash indexes for `id` and `cid` lookups.
601
+ _remove : function(model, options) {
602
+ options || (options = {});
603
+ model = this.getByCid(model) || this.get(model);
604
+ if (!model) return null;
605
+ delete this._byId[model.id];
606
+ delete this._byCid[model.cid];
607
+ this.models.splice(this.indexOf(model), 1);
608
+ this.length--;
609
+ if (!options.silent) model.trigger('remove', model, this, options);
610
+ this._removeReference(model);
611
+ return model;
612
+ },
613
+
614
+ // Internal method to remove a model's ties to a collection.
615
+ _removeReference : function(model) {
616
+ if (this == model.collection) {
617
+ delete model.collection;
618
+ }
619
+ model.unbind('all', this._onModelEvent);
620
+ },
621
+
622
+ // Internal method called every time a model in the set fires an event.
623
+ // Sets need to update their indexes when models change ids. All other
624
+ // events simply proxy through. "add" and "remove" events that originate
625
+ // in other collections are ignored.
626
+ _onModelEvent : function(ev, model, collection, options) {
627
+ if ((ev == 'add' || ev == 'remove') && collection != this) return;
628
+ if (ev == 'destroy') {
629
+ this._remove(model, options);
630
+ }
631
+ if (model && ev === 'change:' + model.idAttribute) {
632
+ delete this._byId[model.previous(model.idAttribute)];
633
+ this._byId[model.id] = model;
634
+ }
635
+ this.trigger.apply(this, arguments);
636
+ }
637
+
638
+ });
639
+
640
+ // Underscore methods that we want to implement on the Collection.
641
+ var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find', 'detect',
642
+ 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include',
643
+ 'invoke', 'max', 'min', 'sortBy', 'sortedIndex', 'toArray', 'size',
644
+ 'first', 'rest', 'last', 'without', 'indexOf', 'lastIndexOf', 'isEmpty'];
645
+
646
+ // Mix in each Underscore method as a proxy to `Collection#models`.
647
+ _.each(methods, function(method) {
648
+ Backbone.Collection.prototype[method] = function() {
649
+ return _[method].apply(_, [this.models].concat(_.toArray(arguments)));
650
+ };
651
+ });
652
+
653
+ // Backbone.Router
654
+ // -------------------
655
+
656
+ // Routers map faux-URLs to actions, and fire events when routes are
657
+ // matched. Creating a new one sets its `routes` hash, if not set statically.
658
+ Backbone.Router = function(options) {
659
+ options || (options = {});
660
+ if (options.routes) this.routes = options.routes;
661
+ this._bindRoutes();
662
+ this.initialize(options);
663
+ };
664
+
665
+ // Cached regular expressions for matching named param parts and splatted
666
+ // parts of route strings.
667
+ var namedParam = /:([\w\d]+)/g;
668
+ var splatParam = /\*([\w\d]+)/g;
669
+ var escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g;
670
+
671
+ // Set up all inheritable **Backbone.Router** properties and methods.
672
+ _.extend(Backbone.Router.prototype, Backbone.Events, {
673
+
674
+ // Initialize is an empty function by default. Override it with your own
675
+ // initialization logic.
676
+ initialize : function(){},
677
+
678
+ // Manually bind a single named route to a callback. For example:
679
+ //
680
+ // this.route('search/:query/p:num', 'search', function(query, num) {
681
+ // ...
682
+ // });
683
+ //
684
+ route : function(route, name, callback) {
685
+ Backbone.history || (Backbone.history = new Backbone.History);
686
+ if (!_.isRegExp(route)) route = this._routeToRegExp(route);
687
+ Backbone.history.route(route, _.bind(function(fragment) {
688
+ var args = this._extractParameters(route, fragment);
689
+ callback.apply(this, args);
690
+ this.trigger.apply(this, ['route:' + name].concat(args));
691
+ }, this));
692
+ },
693
+
694
+ // Simple proxy to `Backbone.history` to save a fragment into the history,
695
+ // without triggering routes.
696
+ saveLocation : function(fragment) {
697
+ Backbone.history.saveLocation(fragment);
698
+ },
699
+
700
+ // Simple proxy to `Backbone.history` to both save a fragment into the
701
+ // history and to then load the route at that fragment.
702
+ setLocation : function(fragment) {
703
+ Backbone.history.saveLocation(fragment);
704
+ Backbone.history.loadUrl(fragment);
705
+ },
706
+
707
+ // Bind all defined routes to `Backbone.history`. We have to reverse the
708
+ // order of the routes here to support behavior where the most general
709
+ // routes can be defined at the bottom of the route map.
710
+ _bindRoutes : function() {
711
+ if (!this.routes) return;
712
+ var routes = [];
713
+ for (var route in this.routes) {
714
+ routes.unshift([route, this.routes[route]]);
715
+ }
716
+ for (var i = 0, l = routes.length; i < l; i++) {
717
+ this.route(routes[i][0], routes[i][1], this[routes[i][1]]);
718
+ }
719
+ },
720
+
721
+ // Convert a route string into a regular expression, suitable for matching
722
+ // against the current location hash.
723
+ _routeToRegExp : function(route) {
724
+ route = route.replace(escapeRegExp, "\\$&")
725
+ .replace(namedParam, "([^\/]*)")
726
+ .replace(splatParam, "(.*?)");
727
+ return new RegExp('^' + route + '$');
728
+ },
729
+
730
+ // Given a route, and a URL fragment that it matches, return the array of
731
+ // extracted parameters.
732
+ _extractParameters : function(route, fragment) {
733
+ return route.exec(fragment).slice(1);
734
+ }
735
+
736
+ });
737
+
738
+ // Backbone.History
739
+ // ----------------
740
+
741
+ // Handles cross-browser history management, based on URL fragments. If the
742
+ // browser does not support `onhashchange`, falls back to polling.
743
+ Backbone.History = function() {
744
+ this.handlers = [];
745
+ _.bindAll(this, 'checkUrl');
746
+ };
747
+
748
+ // Cached regex for cleaning hashes.
749
+ var hashStrip = /^#*!?/;
750
+
751
+ // Cached regex for detecting MSIE.
752
+ var isExplorer = /msie [\w.]+/;
753
+
754
+ // Has the history handling already been started?
755
+ var historyStarted = false;
756
+
757
+ // Set up all inheritable **Backbone.History** properties and methods.
758
+ _.extend(Backbone.History.prototype, {
759
+
760
+ // The default interval to poll for hash changes, if necessary, is
761
+ // twenty times a second.
762
+ interval: 50,
763
+
764
+ // Get the cross-browser normalized URL fragment, either from the URL,
765
+ // the hash, or the override.
766
+ getFragment : function(fragment, forcePushState) {
767
+ if (fragment == null) {
768
+ if (this._hasPushState || forcePushState) {
769
+ fragment = window.location.pathname;
770
+ var search = window.location.search;
771
+ if (search) fragment += search;
772
+ if (fragment.indexOf(this.options.root) == 0) fragment = fragment.substr(this.options.root.length);
773
+ } else {
774
+ fragment = window.location.hash;
775
+ }
776
+ }
777
+ return fragment.replace(hashStrip, '');
778
+ },
779
+
780
+ // Start the hash change handling, returning `true` if the current URL matches
781
+ // an existing route, and `false` otherwise.
782
+ start : function(options) {
783
+
784
+ // Figure out the initial configuration. Do we need an iframe?
785
+ // Is pushState desired ... is it available?
786
+ if (historyStarted) throw new Error("Backbone.history has already been started");
787
+ this.options = _.extend({}, {root: '/'}, this.options, options);
788
+ this._wantsPushState = !!this.options.pushState;
789
+ this._hasPushState = !!(this.options.pushState && window.history && window.history.pushState);
790
+ var fragment = this.getFragment();
791
+ var docMode = document.documentMode;
792
+ var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
793
+ if (oldIE) {
794
+ this.iframe = $('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
795
+ this.saveLocation(fragment);
796
+ }
797
+
798
+ // Depending on whether we're using pushState or hashes, and whether
799
+ // 'onhashchange' is supported, determine how we check the URL state.
800
+ if (this._hasPushState) {
801
+ $(window).bind('popstate', this.checkUrl);
802
+ } else if ('onhashchange' in window && !oldIE) {
803
+ $(window).bind('hashchange', this.checkUrl);
804
+ } else {
805
+ setInterval(this.checkUrl, this.interval);
806
+ }
807
+
808
+ // Determine if we need to change the base url, for a pushState link
809
+ // opened by a non-pushState browser.
810
+ this.fragment = fragment;
811
+ historyStarted = true;
812
+ var started = this.loadUrl() || this.loadUrl(window.location.hash);
813
+ if (this._wantsPushState && !this._hasPushState && window.location.pathname != this.options.root) {
814
+ this.fragment = this.getFragment(null, true);
815
+ window.location = this.options.root + '#' + this.fragment;
816
+ } else {
817
+ return started;
818
+ }
819
+ },
820
+
821
+ // Add a route to be tested when the fragment changes. Routes added later may
822
+ // override previous routes.
823
+ route : function(route, callback) {
824
+ this.handlers.unshift({route : route, callback : callback});
825
+ },
826
+
827
+ // Checks the current URL to see if it has changed, and if it has,
828
+ // calls `loadUrl`, normalizing across the hidden iframe.
829
+ checkUrl : function(e) {
830
+ var current = this.getFragment();
831
+ if (current == this.fragment && this.iframe) current = this.getFragment(this.iframe.location.hash);
832
+ if (current == this.fragment || current == decodeURIComponent(this.fragment)) return false;
833
+ if (this.iframe) this.saveLocation(current);
834
+ this.loadUrl() || this.loadUrl(window.location.hash);
835
+ },
836
+
837
+ // Attempt to load the current URL fragment. If a route succeeds with a
838
+ // match, returns `true`. If no defined routes matches the fragment,
839
+ // returns `false`.
840
+ loadUrl : function(fragmentOverride) {
841
+ var fragment = this.fragment = this.getFragment(fragmentOverride);
842
+ var matched = _.any(this.handlers, function(handler) {
843
+ if (handler.route.test(fragment)) {
844
+ handler.callback(fragment);
845
+ return true;
846
+ }
847
+ });
848
+ return matched;
849
+ },
850
+
851
+ // Save a fragment into the hash history. You are responsible for properly
852
+ // URL-encoding the fragment in advance. This does not trigger
853
+ // a `hashchange` event.
854
+ saveLocation : function(fragment) {
855
+ fragment = (fragment || '').replace(hashStrip, '');
856
+ if (this.fragment == fragment || this.fragment == decodeURIComponent(fragment)) return;
857
+ if (this._hasPushState) {
858
+ var loc = window.location;
859
+ if (fragment.indexOf(this.options.root) != 0) fragment = this.options.root + fragment;
860
+ this.fragment = fragment;
861
+ window.history.pushState({}, document.title, loc.protocol + '//' + loc.host + fragment);
862
+ } else {
863
+ window.location.hash = this.fragment = fragment;
864
+ if (this.iframe && (fragment != this.getFragment(this.iframe.location.hash))) {
865
+ this.iframe.document.open().close();
866
+ this.iframe.location.hash = fragment;
867
+ }
868
+ }
869
+ }
870
+
871
+ });
872
+
873
+ // Backbone.View
874
+ // -------------
875
+
876
+ // Creating a Backbone.View creates its initial element outside of the DOM,
877
+ // if an existing element is not provided...
878
+ Backbone.View = function(options) {
879
+ this.cid = _.uniqueId('view');
880
+ this._configure(options || {});
881
+ this._ensureElement();
882
+ this.delegateEvents();
883
+ this.initialize(options);
884
+ };
885
+
886
+ // Element lookup, scoped to DOM elements within the current view.
887
+ // This should be prefered to global lookups, if you're dealing with
888
+ // a specific view.
889
+ var selectorDelegate = function(selector) {
890
+ return $(selector, this.el);
891
+ };
892
+
893
+ // Cached regex to split keys for `delegate`.
894
+ var eventSplitter = /^(\S+)\s*(.*)$/;
895
+
896
+ // List of view options to be merged as properties.
897
+ var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName'];
898
+
899
+ // Set up all inheritable **Backbone.View** properties and methods.
900
+ _.extend(Backbone.View.prototype, Backbone.Events, {
901
+
902
+ // The default `tagName` of a View's element is `"div"`.
903
+ tagName : 'div',
904
+
905
+ // Attach the `selectorDelegate` function as the `$` property.
906
+ $ : selectorDelegate,
907
+
908
+ // Initialize is an empty function by default. Override it with your own
909
+ // initialization logic.
910
+ initialize : function(){},
911
+
912
+ // **render** is the core function that your view should override, in order
913
+ // to populate its element (`this.el`), with the appropriate HTML. The
914
+ // convention is for **render** to always return `this`.
915
+ render : function() {
916
+ return this;
917
+ },
918
+
919
+ // Remove this view from the DOM. Note that the view isn't present in the
920
+ // DOM by default, so calling this method may be a no-op.
921
+ remove : function() {
922
+ $(this.el).remove();
923
+ return this;
924
+ },
925
+
926
+ // For small amounts of DOM Elements, where a full-blown template isn't
927
+ // needed, use **make** to manufacture elements, one at a time.
928
+ //
929
+ // var el = this.make('li', {'class': 'row'}, this.model.escape('title'));
930
+ //
931
+ make : function(tagName, attributes, content) {
932
+ var el = document.createElement(tagName);
933
+ if (attributes) $(el).attr(attributes);
934
+ if (content) $(el).html(content);
935
+ return el;
936
+ },
937
+
938
+ // Set callbacks, where `this.callbacks` is a hash of
939
+ //
940
+ // *{"event selector": "callback"}*
941
+ //
942
+ // {
943
+ // 'mousedown .title': 'edit',
944
+ // 'click .button': 'save'
945
+ // }
946
+ //
947
+ // pairs. Callbacks will be bound to the view, with `this` set properly.
948
+ // Uses event delegation for efficiency.
949
+ // Omitting the selector binds the event to `this.el`.
950
+ // This only works for delegate-able events: not `focus`, `blur`, and
951
+ // not `change`, `submit`, and `reset` in Internet Explorer.
952
+ delegateEvents : function(events) {
953
+ if (!(events || (events = this.events))) return;
954
+ $(this.el).unbind('.delegateEvents' + this.cid);
955
+ for (var key in events) {
956
+ var methodName = events[key];
957
+ var match = key.match(eventSplitter);
958
+ var eventName = match[1], selector = match[2];
959
+ var method = _.bind(this[methodName], this);
960
+ eventName += '.delegateEvents' + this.cid;
961
+ if (selector === '') {
962
+ $(this.el).bind(eventName, method);
963
+ } else {
964
+ $(this.el).delegate(selector, eventName, method);
965
+ }
966
+ }
967
+ },
968
+
969
+ // Performs the initial configuration of a View with a set of options.
970
+ // Keys with special meaning *(model, collection, id, className)*, are
971
+ // attached directly to the view.
972
+ _configure : function(options) {
973
+ if (this.options) options = _.extend({}, this.options, options);
974
+ for (var i = 0, l = viewOptions.length; i < l; i++) {
975
+ var attr = viewOptions[i];
976
+ if (options[attr]) this[attr] = options[attr];
977
+ }
978
+ this.options = options;
979
+ },
980
+
981
+ // Ensure that the View has a DOM element to render into.
982
+ // If `this.el` is a string, pass it through `$()`, take the first
983
+ // matching element, and re-assign it to `el`. Otherwise, create
984
+ // an element from the `id`, `className` and `tagName` proeprties.
985
+ _ensureElement : function() {
986
+ if (!this.el) {
987
+ var attrs = this.attributes || {};
988
+ if (this.id) attrs.id = this.id;
989
+ if (this.className) attrs['class'] = this.className;
990
+ this.el = this.make(this.tagName, attrs);
991
+ } else if (_.isString(this.el)) {
992
+ this.el = $(this.el).get(0);
993
+ }
994
+ }
995
+
996
+ });
997
+
998
+ // The self-propagating extend function that Backbone classes use.
999
+ var extend = function (protoProps, classProps) {
1000
+ var child = inherits(this, protoProps, classProps);
1001
+ child.extend = this.extend;
1002
+ return child;
1003
+ };
1004
+
1005
+ // Set up inheritance for the model, collection, and view.
1006
+ Backbone.Model.extend = Backbone.Collection.extend =
1007
+ Backbone.Router.extend = Backbone.View.extend = extend;
1008
+
1009
+ // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
1010
+ var methodMap = {
1011
+ 'create': 'POST',
1012
+ 'update': 'PUT',
1013
+ 'delete': 'DELETE',
1014
+ 'read' : 'GET'
1015
+ };
1016
+
1017
+ // Backbone.sync
1018
+ // -------------
1019
+
1020
+ // Override this function to change the manner in which Backbone persists
1021
+ // models to the server. You will be passed the type of request, and the
1022
+ // model in question. By default, uses makes a RESTful Ajax request
1023
+ // to the model's `url()`. Some possible customizations could be:
1024
+ //
1025
+ // * Use `setTimeout` to batch rapid-fire updates into a single request.
1026
+ // * Send up the models as XML instead of JSON.
1027
+ // * Persist models via WebSockets instead of Ajax.
1028
+ //
1029
+ // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
1030
+ // as `POST`, with a `_method` parameter containing the true HTTP method,
1031
+ // as well as all requests with the body as `application/x-www-form-urlencoded` instead of
1032
+ // `application/json` with the model in a param named `model`.
1033
+ // Useful when interfacing with server-side languages like **PHP** that make
1034
+ // it difficult to read the body of `PUT` requests.
1035
+ Backbone.sync = function(method, model, options) {
1036
+ var type = methodMap[method];
1037
+
1038
+ // Default JSON-request options.
1039
+ var params = _.extend({
1040
+ type: type,
1041
+ dataType: 'json',
1042
+ processData: false
1043
+ }, options);
1044
+
1045
+ // Ensure that we have a URL.
1046
+ if (!params.url) {
1047
+ params.url = getUrl(model) || urlError();
1048
+ }
1049
+
1050
+ // Ensure that we have the appropriate request data.
1051
+ if (!params.data && model && (method == 'create' || method == 'update')) {
1052
+ params.contentType = 'application/json';
1053
+ params.data = JSON.stringify(model.toJSON());
1054
+ }
1055
+
1056
+ // For older servers, emulate JSON by encoding the request into an HTML-form.
1057
+ if (Backbone.emulateJSON) {
1058
+ params.contentType = 'application/x-www-form-urlencoded';
1059
+ params.processData = true;
1060
+ params.data = params.data ? {model : params.data} : {};
1061
+ }
1062
+
1063
+ // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
1064
+ // And an `X-HTTP-Method-Override` header.
1065
+ if (Backbone.emulateHTTP) {
1066
+ if (type === 'PUT' || type === 'DELETE') {
1067
+ if (Backbone.emulateJSON) params.data._method = type;
1068
+ params.type = 'POST';
1069
+ params.beforeSend = function(xhr) {
1070
+ xhr.setRequestHeader('X-HTTP-Method-Override', type);
1071
+ };
1072
+ }
1073
+ }
1074
+
1075
+ // Make the request.
1076
+ return $.ajax(params);
1077
+ };
1078
+
1079
+ // Helpers
1080
+ // -------
1081
+
1082
+ // Shared empty constructor function to aid in prototype-chain creation.
1083
+ var ctor = function(){};
1084
+
1085
+ // Helper function to correctly set up the prototype chain, for subclasses.
1086
+ // Similar to `goog.inherits`, but uses a hash of prototype properties and
1087
+ // class properties to be extended.
1088
+ var inherits = function(parent, protoProps, staticProps) {
1089
+ var child;
1090
+
1091
+ // The constructor function for the new subclass is either defined by you
1092
+ // (the "constructor" property in your `extend` definition), or defaulted
1093
+ // by us to simply call `super()`.
1094
+ if (protoProps && protoProps.hasOwnProperty('constructor')) {
1095
+ child = protoProps.constructor;
1096
+ } else {
1097
+ child = function(){ return parent.apply(this, arguments); };
1098
+ }
1099
+
1100
+ // Inherit class (static) properties from parent.
1101
+ _.extend(child, parent);
1102
+
1103
+ // Set the prototype chain to inherit from `parent`, without calling
1104
+ // `parent`'s constructor function.
1105
+ ctor.prototype = parent.prototype;
1106
+ child.prototype = new ctor();
1107
+
1108
+ // Add prototype properties (instance properties) to the subclass,
1109
+ // if supplied.
1110
+ if (protoProps) _.extend(child.prototype, protoProps);
1111
+
1112
+ // Add static properties to the constructor function, if supplied.
1113
+ if (staticProps) _.extend(child, staticProps);
1114
+
1115
+ // Correctly set child's `prototype.constructor`.
1116
+ child.prototype.constructor = child;
1117
+
1118
+ // Set a convenience property in case the parent's prototype is needed later.
1119
+ child.__super__ = parent.prototype;
1120
+
1121
+ return child;
1122
+ };
1123
+
1124
+ // Helper function to get a URL from a Model or Collection as a property
1125
+ // or as a function.
1126
+ var getUrl = function(object) {
1127
+ if (!(object && object.url)) return null;
1128
+ return _.isFunction(object.url) ? object.url() : object.url;
1129
+ };
1130
+
1131
+ // Throw an error when a URL is needed, and none is supplied.
1132
+ var urlError = function() {
1133
+ throw new Error("A 'url' property or function must be specified");
1134
+ };
1135
+
1136
+ // Wrap an optional error callback with a fallback error event.
1137
+ var wrapError = function(onError, model, options) {
1138
+ return function(resp) {
1139
+ if (onError) {
1140
+ onError(model, resp, options);
1141
+ } else {
1142
+ model.trigger('error', model, resp, options);
1143
+ }
1144
+ };
1145
+ };
1146
+
1147
+ // Helper function to escape a string for HTML rendering.
1148
+ var escapeHTML = function(string) {
1149
+ return string.replace(/&(?!\w+;|#\d+;|#x[\da-f]+;)/gi, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27').replace(/\//g,'&#x2F;');
1150
+ };
1151
+
1152
+ }).call(this);