bbr-wsm 1.1.0

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