backbonejs-rails 0.0.7 → 1.0.0

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