tableling-rails 0.0.16 → 0.0.17

Sign up to get free protection for your applications and to get access to all the features.
Files changed (71) hide show
  1. data/lib/tableling-rails/version.rb +1 -1
  2. data/spec/dummy/db/development.sqlite3 +0 -0
  3. data/spec/dummy/db/test.sqlite3 +0 -0
  4. data/spec/dummy/log/development.log +54 -7512
  5. data/spec/dummy/log/test.log +22 -1
  6. data/vendor/assets/javascripts/tableling.backbone.js +1315 -977
  7. data/vendor/assets/javascripts/tableling.js +2 -2
  8. data/vendor/assets/javascripts/tableling.world.js +1604 -1224
  9. metadata +3 -127
  10. data/spec/dummy/tmp/cache/assets/BF1/770/sprockets%2F8228a53c539c582499241527570aa216 +0 -0
  11. data/spec/dummy/tmp/cache/assets/C3F/0C0/sprockets%2F4643701467ac62c314510c8dd021916f +0 -0
  12. data/spec/dummy/tmp/cache/assets/C53/AD0/sprockets%2F712078516a81502575c831cb0a8e898e +0 -0
  13. data/spec/dummy/tmp/cache/assets/C59/0F0/sprockets%2F099f4e84a443568245ff0674030f6e05 +0 -0
  14. data/spec/dummy/tmp/cache/assets/C60/CF0/sprockets%2F32a45292ee67867d8715952f3072ad84 +0 -0
  15. data/spec/dummy/tmp/cache/assets/C6F/0E0/sprockets%2F82372776487d948ef7666d304d6fb345 +0 -0
  16. data/spec/dummy/tmp/cache/assets/C80/840/sprockets%2F562c2d168da585f80579347d10790a0a +0 -0
  17. data/spec/dummy/tmp/cache/assets/C82/F20/sprockets%2F117015d65237e3682f5b21c87d58ab95 +0 -0
  18. data/spec/dummy/tmp/cache/assets/C86/280/sprockets%2F1345c9947753f018f45371ec5083fa2d +0 -0
  19. data/spec/dummy/tmp/cache/assets/C91/350/sprockets%2F6864c49a10954375948d9f306db308fb +0 -0
  20. data/spec/dummy/tmp/cache/assets/C9A/900/sprockets%2Fc1b5b7611d7c10e124512724f29f241d +0 -0
  21. data/spec/dummy/tmp/cache/assets/CAF/540/sprockets%2F8f42e689b84f0b25c0180046467adf31 +0 -0
  22. data/spec/dummy/tmp/cache/assets/CB1/9A0/sprockets%2F57805dfa396248a9665cb4a0c85116d0 +0 -0
  23. data/spec/dummy/tmp/cache/assets/CC1/4E0/sprockets%2F6ef77414c793c84a437244d7d965ba90 +0 -0
  24. data/spec/dummy/tmp/cache/assets/CC3/B10/sprockets%2F0a2c59284c7a5d99581883a9763b5ad8 +0 -0
  25. data/spec/dummy/tmp/cache/assets/CC9/940/sprockets%2F8128c279185cf97dba7914278ce838b4 +0 -0
  26. data/spec/dummy/tmp/cache/assets/CCA/0C0/sprockets%2F6c3e053393afe303432ca73f1b41490b +0 -0
  27. data/spec/dummy/tmp/cache/assets/CD5/2C0/sprockets%2F166c056119ebdfb8b7104c97b424b423 +0 -0
  28. data/spec/dummy/tmp/cache/assets/CDB/610/sprockets%2F7adf20860b018477a95cdb8321b49d16 +0 -0
  29. data/spec/dummy/tmp/cache/assets/CDD/F50/sprockets%2F7353f31f80f1139aade47728a62af336 +0 -0
  30. data/spec/dummy/tmp/cache/assets/CE9/760/sprockets%2F5ae7fab601683996918936cad21fc244 +0 -0
  31. data/spec/dummy/tmp/cache/assets/CE9/B90/sprockets%2Fea2eb066933b1d8b5949972c3c79353a +0 -0
  32. data/spec/dummy/tmp/cache/assets/CF1/AF0/sprockets%2F14dc9633b61024231ebec0c1a4a0259f +0 -0
  33. data/spec/dummy/tmp/cache/assets/D02/340/sprockets%2Fae58ed66f72137a594b0912bab600e03 +0 -0
  34. data/spec/dummy/tmp/cache/assets/D0A/AC0/sprockets%2Fc154991d0a7564e15c0fb4a555c5c73d +0 -0
  35. data/spec/dummy/tmp/cache/assets/D0B/190/sprockets%2F68cb0d1054ca546fc473274c4ac8737c +0 -0
  36. data/spec/dummy/tmp/cache/assets/D11/530/sprockets%2F13bc8c66140adef2e97648630866aae3 +0 -0
  37. data/spec/dummy/tmp/cache/assets/D16/AA0/sprockets%2Ff181e659a47e2cf9c257f32d80452bd3 +0 -0
  38. data/spec/dummy/tmp/cache/assets/D18/840/sprockets%2F50c1885539f61359c48af74fcae1df31 +0 -0
  39. data/spec/dummy/tmp/cache/assets/D1B/940/sprockets%2F7c4819d1dd9b64a22941d8c7bd1e6954 +0 -0
  40. data/spec/dummy/tmp/cache/assets/D2B/1F0/sprockets%2F6a4c116e8316d082bb0ffae02e94b107 +0 -0
  41. data/spec/dummy/tmp/cache/assets/D3C/E20/sprockets%2Ffc6c44ec250bc532c55649e5292b5c1f +0 -0
  42. data/spec/dummy/tmp/cache/assets/D4B/C30/sprockets%2Fe8aa746e637d69ff0ac1e71e528c5292 +0 -0
  43. data/spec/dummy/tmp/cache/assets/D4E/1B0/sprockets%2Ff7cbd26ba1d28d48de824f0e94586655 +0 -0
  44. data/spec/dummy/tmp/cache/assets/D5A/E20/sprockets%2Febf23d670481ba70b341aa2eb6e37b08 +0 -0
  45. data/spec/dummy/tmp/cache/assets/D5C/1F0/sprockets%2F2d3f2cfd98bf787168fb59f84ab24784 +0 -0
  46. data/spec/dummy/tmp/cache/assets/D5D/C60/sprockets%2Ffa0336b42d01aa9173d9d4c12fc4e82d +0 -0
  47. data/spec/dummy/tmp/cache/assets/D65/DD0/sprockets%2Fed4503679ef66f0e597bfc738bc9e698 +0 -0
  48. data/spec/dummy/tmp/cache/assets/D68/930/sprockets%2F5a15e52e84502f9fceb7ea04020f65fc +0 -0
  49. data/spec/dummy/tmp/cache/assets/D8C/140/sprockets%2F2afdbb3902a1be5d2f045cfc837903a3 +0 -0
  50. data/spec/dummy/tmp/cache/assets/D8E/660/sprockets%2F3a3eed926bdf64000ccacb36022f78d4 +0 -0
  51. data/spec/dummy/tmp/cache/assets/D95/690/sprockets%2Fe4d19a04705ee5d72c7fa64dc2070ddb +0 -0
  52. data/spec/dummy/tmp/cache/assets/DA4/EC0/sprockets%2F8da2289e16c1d0cac94aa825ee18d99d +0 -0
  53. data/spec/dummy/tmp/cache/assets/DA6/120/sprockets%2Fc5880aca76ccbb51f9388362e8afc1e6 +0 -0
  54. data/spec/dummy/tmp/cache/assets/DA7/390/sprockets%2F25e744cd1b6f8f7ce1d52c1e86a8f19a +0 -0
  55. data/spec/dummy/tmp/cache/assets/DAB/3E0/sprockets%2F63d2fa621beec4fe878f9eb2884426ab +0 -0
  56. data/spec/dummy/tmp/cache/assets/DAB/660/sprockets%2F9a8c36769afcc7027b4b6ee0c3e77ce5 +0 -0
  57. data/spec/dummy/tmp/cache/assets/DBF/EB0/sprockets%2F2afcec323c8ba12a2b7c852f23aa589e +0 -0
  58. data/spec/dummy/tmp/cache/assets/DCE/9F0/sprockets%2F8fa8c08ea8da97c06cd6c32fe3e613b0 +0 -0
  59. data/spec/dummy/tmp/cache/assets/DCF/E50/sprockets%2Fc39ff2ed4e1fb4269c39d415acf0d90b +0 -0
  60. data/spec/dummy/tmp/cache/assets/DD8/0A0/sprockets%2Fb2c3097effcd6084ec75e1f745d1d7dd +0 -0
  61. data/spec/dummy/tmp/cache/assets/DDC/400/sprockets%2Fcffd775d018f68ce5dba1ee0d951a994 +0 -0
  62. data/spec/dummy/tmp/cache/assets/DF0/040/sprockets%2F04bbbe1ee5ca914173cd90cf6e8a4e0b +0 -0
  63. data/spec/dummy/tmp/cache/assets/DF7/C80/sprockets%2Ff503b3666caf04beb7cfe54cbdb0575e +0 -0
  64. data/spec/dummy/tmp/cache/assets/DFA/B70/sprockets%2F262fb95d3f7cfc16febb0f0128ac38ce +0 -0
  65. data/spec/dummy/tmp/cache/assets/E03/260/sprockets%2Fd1fcfea59ff53c32557ffcd93016cb2e +0 -0
  66. data/spec/dummy/tmp/cache/assets/E04/890/sprockets%2F2f5173deea6c795b8fdde723bb4b63af +0 -0
  67. data/spec/dummy/tmp/cache/assets/E0A/510/sprockets%2F8efee416ba436e75bea85d4d367faea7 +0 -0
  68. data/spec/dummy/tmp/cache/assets/E43/810/sprockets%2F79b0ef75ceb26a9c8fca797db3efba96 +0 -0
  69. data/spec/dummy/tmp/cache/assets/E96/1B0/sprockets%2F6d5fe51f9c1a3d2f898becd0bcddef3e +0 -0
  70. data/spec/dummy/tmp/cache/assets/ED4/410/sprockets%2F082adbb8e2abd8a21c8b34aebbbfbfad +0 -0
  71. data/spec/dummy/tmp/pids/server.pid +0 -1
@@ -1,7 +1,28 @@
1
1
  Connecting to database specified by database.yml
2
-  (0.1ms) SELECT "schema_migrations"."version" FROM "schema_migrations" 
2
+  (2.2ms) SELECT "schema_migrations"."version" FROM "schema_migrations" 
3
3
  Migrating to CreateBooks (20121008115302)
4
4
   (0.1ms) begin transaction
5
+  (0.1ms) rollback transaction
6
+  (0.0ms) begin transaction
5
7
   (0.0ms) rollback transaction
8
+ Connecting to database specified by database.yml
9
+  (2.5ms) SELECT "schema_migrations"."version" FROM "schema_migrations" 
10
+ Migrating to CreateBooks (20121008115302)
11
+  (0.1ms) begin transaction
12
+  (0.1ms) rollback transaction
6
13
   (0.0ms) begin transaction
7
14
   (0.0ms) rollback transaction
15
+ Connecting to database specified by database.yml
16
+  (1.9ms) SELECT "schema_migrations"."version" FROM "schema_migrations" 
17
+ Migrating to CreateBooks (20121008115302)
18
+  (0.1ms) begin transaction
19
+  (0.1ms) rollback transaction
20
+  (0.1ms) begin transaction
21
+  (0.0ms) rollback transaction
22
+ Connecting to database specified by database.yml
23
+  (1.9ms) SELECT "schema_migrations"."version" FROM "schema_migrations" 
24
+ Migrating to CreateBooks (20121008115302)
25
+  (0.1ms) begin transaction
26
+  (0.0ms) rollback transaction
27
+  (0.0ms) begin transaction
28
+  (0.1ms) rollback transaction
@@ -1,6 +1,6 @@
1
- // Backbone.js 0.9.10
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
@@ -18,14 +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 array methods.
21
+ // Create local references to array methods we'll want to use later.
22
22
  var array = [];
23
23
  var push = array.push;
24
24
  var slice = array.slice;
25
25
  var splice = array.splice;
26
26
 
27
27
  // The top-level namespace. All public Backbone classes and modules will
28
- // be attached to this. Exported for both CommonJS and the browser.
28
+ // be attached to this. Exported for both the browser and the server.
29
29
  var Backbone;
30
30
  if (typeof exports !== 'undefined') {
31
31
  Backbone = exports;
@@ -34,14 +34,15 @@
34
34
  }
35
35
 
36
36
  // Current version of the library. Keep in sync with `package.json`.
37
- Backbone.VERSION = '0.9.10';
37
+ Backbone.VERSION = '1.0.0';
38
38
 
39
39
  // Require Underscore, if we're on the server, and it's not already present.
40
40
  var _ = root._;
41
41
  if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
42
42
 
43
- // For Backbone's purposes, jQuery, Zepto, or Ender owns the `$` variable.
44
- Backbone.$ = root.jQuery || root.Zepto || root.ender;
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.$;
45
46
 
46
47
  // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
47
48
  // to its previous owner. Returns a reference to this Backbone object.
@@ -64,45 +65,6 @@
64
65
  // Backbone.Events
65
66
  // ---------------
66
67
 
67
- // Regular expression used to split event strings.
68
- var eventSplitter = /\s+/;
69
-
70
- // Implement fancy features of the Events API such as multiple event
71
- // names `"change blur"` and jQuery-style event maps `{change: action}`
72
- // in terms of the existing API.
73
- var eventsApi = function(obj, action, name, rest) {
74
- if (!name) return true;
75
- if (typeof name === 'object') {
76
- for (var key in name) {
77
- obj[action].apply(obj, [key, name[key]].concat(rest));
78
- }
79
- } else if (eventSplitter.test(name)) {
80
- var names = name.split(eventSplitter);
81
- for (var i = 0, l = names.length; i < l; i++) {
82
- obj[action].apply(obj, [names[i]].concat(rest));
83
- }
84
- } else {
85
- return true;
86
- }
87
- };
88
-
89
- // Optimized internal dispatch function for triggering events. Tries to
90
- // keep the usual cases speedy (most Backbone events have 3 arguments).
91
- var triggerEvents = function(events, args) {
92
- var ev, i = -1, l = events.length;
93
- switch (args.length) {
94
- case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx);
95
- return;
96
- case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, args[0]);
97
- return;
98
- case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, args[0], args[1]);
99
- return;
100
- case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, args[0], args[1], args[2]);
101
- return;
102
- default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
103
- }
104
- };
105
-
106
68
  // A module that can be mixed in to *any object* in order to provide it with
107
69
  // custom events. You may bind with `on` or remove with `off` callback
108
70
  // functions to an event; `trigger`-ing an event fires all callbacks in
@@ -115,29 +77,27 @@
115
77
  //
116
78
  var Events = Backbone.Events = {
117
79
 
118
- // Bind one or more space separated events, or an events map,
119
- // to a `callback` function. Passing `"all"` will bind the callback to
120
- // all events fired.
80
+ // Bind an event to a `callback` function. Passing `"all"` will bind
81
+ // the callback to all events fired.
121
82
  on: function(name, callback, context) {
122
- if (!(eventsApi(this, 'on', name, [callback, context]) && callback)) return this;
83
+ if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
123
84
  this._events || (this._events = {});
124
- var list = this._events[name] || (this._events[name] = []);
125
- list.push({callback: callback, context: context, ctx: context || this});
85
+ var events = this._events[name] || (this._events[name] = []);
86
+ events.push({callback: callback, context: context, ctx: context || this});
126
87
  return this;
127
88
  },
128
89
 
129
- // Bind events to only be triggered a single time. After the first time
90
+ // Bind an event to only be triggered a single time. After the first time
130
91
  // the callback is invoked, it will be removed.
131
92
  once: function(name, callback, context) {
132
- if (!(eventsApi(this, 'once', name, [callback, context]) && callback)) return this;
93
+ if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this;
133
94
  var self = this;
134
95
  var once = _.once(function() {
135
96
  self.off(name, once);
136
97
  callback.apply(this, arguments);
137
98
  });
138
99
  once._callback = callback;
139
- this.on(name, once, context);
140
- return this;
100
+ return this.on(name, once, context);
141
101
  },
142
102
 
143
103
  // Remove one or many callbacks. If `context` is null, removes all
@@ -145,7 +105,7 @@
145
105
  // callbacks for the event. If `name` is null, removes all bound
146
106
  // callbacks for all events.
147
107
  off: function(name, callback, context) {
148
- var list, ev, events, names, i, l, j, k;
108
+ var retain, ev, events, names, i, l, j, k;
149
109
  if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
150
110
  if (!name && !callback && !context) {
151
111
  this._events = {};
@@ -155,19 +115,18 @@
155
115
  names = name ? [name] : _.keys(this._events);
156
116
  for (i = 0, l = names.length; i < l; i++) {
157
117
  name = names[i];
158
- if (list = this._events[name]) {
159
- events = [];
118
+ if (events = this._events[name]) {
119
+ this._events[name] = retain = [];
160
120
  if (callback || context) {
161
- for (j = 0, k = list.length; j < k; j++) {
162
- ev = list[j];
163
- if ((callback && callback !== ev.callback &&
164
- callback !== ev.callback._callback) ||
121
+ for (j = 0, k = events.length; j < k; j++) {
122
+ ev = events[j];
123
+ if ((callback && callback !== ev.callback && callback !== ev.callback._callback) ||
165
124
  (context && context !== ev.context)) {
166
- events.push(ev);
125
+ retain.push(ev);
167
126
  }
168
127
  }
169
128
  }
170
- this._events[name] = events;
129
+ if (!retain.length) delete this._events[name];
171
130
  }
172
131
  }
173
132
 
@@ -189,35 +148,82 @@
189
148
  return this;
190
149
  },
191
150
 
192
- // An inversion-of-control version of `on`. Tell *this* object to listen to
193
- // an event in another object ... keeping track of what it's listening to.
194
- listenTo: function(obj, name, callback) {
195
- var listeners = this._listeners || (this._listeners = {});
196
- var id = obj._listenerId || (obj._listenerId = _.uniqueId('l'));
197
- listeners[id] = obj;
198
- obj.on(name, typeof name === 'object' ? this : callback, this);
199
- return this;
200
- },
201
-
202
151
  // Tell this object to stop listening to either specific events ... or
203
152
  // to every object it's currently listening to.
204
153
  stopListening: function(obj, name, callback) {
205
154
  var listeners = this._listeners;
206
- if (!listeners) return;
207
- if (obj) {
208
- obj.off(name, typeof name === 'object' ? this : callback, this);
209
- if (!name && !callback) delete listeners[obj._listenerId];
210
- } else {
211
- if (typeof name === 'object') callback = this;
212
- for (var id in listeners) {
213
- listeners[id].off(name, callback, this);
214
- }
215
- 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];
216
162
  }
217
163
  return this;
218
164
  }
165
+
166
+ };
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
+ }
219
209
  };
220
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
+
221
227
  // Aliases for backwards compatibility.
222
228
  Events.bind = Events.on;
223
229
  Events.unbind = Events.off;
@@ -229,15 +235,21 @@
229
235
  // Backbone.Model
230
236
  // --------------
231
237
 
232
- // 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`)
233
244
  // is automatically generated and assigned for you.
234
245
  var Model = Backbone.Model = function(attributes, options) {
235
246
  var defaults;
236
247
  var attrs = attributes || {};
248
+ options || (options = {});
237
249
  this.cid = _.uniqueId('c');
238
250
  this.attributes = {};
239
- if (options && options.collection) this.collection = options.collection;
240
- if (options && options.parse) attrs = this.parse(attrs, options) || {};
251
+ _.extend(this, _.pick(options, modelOptions));
252
+ if (options.parse) attrs = this.parse(attrs, options) || {};
241
253
  if (defaults = _.result(this, 'defaults')) {
242
254
  attrs = _.defaults({}, attrs, defaults);
243
255
  }
@@ -246,12 +258,18 @@
246
258
  this.initialize.apply(this, arguments);
247
259
  };
248
260
 
261
+ // A list of options to be attached directly to the model, if provided.
262
+ var modelOptions = ['url', 'urlRoot', 'collection'];
263
+
249
264
  // Attach all inheritable methods to the Model prototype.
250
265
  _.extend(Model.prototype, Events, {
251
266
 
252
267
  // A hash of attributes whose current and previous value differ.
253
268
  changed: null,
254
269
 
270
+ // The value returned during the last failed validation.
271
+ validationError: null,
272
+
255
273
  // The default name for the JSON `id` attribute is `"id"`. MongoDB and
256
274
  // CouchDB users may want to set this to `"_id"`.
257
275
  idAttribute: 'id',
@@ -265,7 +283,8 @@
265
283
  return _.clone(this.attributes);
266
284
  },
267
285
 
268
- // Proxy `Backbone.sync` by default.
286
+ // Proxy `Backbone.sync` by default -- but override this if you need
287
+ // custom syncing semantics for *this* particular model.
269
288
  sync: function() {
270
289
  return Backbone.sync.apply(this, arguments);
271
290
  },
@@ -286,10 +305,9 @@
286
305
  return this.get(attr) != null;
287
306
  },
288
307
 
289
- // ----------------------------------------------------------------------
290
-
291
- // Set a hash of model attributes on the object, firing `"change"` unless
292
- // you choose to silence it.
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.
293
311
  set: function(key, val, options) {
294
312
  var attr, attrs, unset, changes, silent, changing, prev, current;
295
313
  if (key == null) return this;
@@ -343,6 +361,8 @@
343
361
  }
344
362
  }
345
363
 
364
+ // You might be wondering why there's a `while` loop here. Changes can
365
+ // be recursively nested within `"change"` events.
346
366
  if (changing) return this;
347
367
  if (!silent) {
348
368
  while (this._pending) {
@@ -355,14 +375,13 @@
355
375
  return this;
356
376
  },
357
377
 
358
- // Remove an attribute from the model, firing `"change"` unless you choose
359
- // 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.
360
380
  unset: function(attr, options) {
361
381
  return this.set(attr, void 0, _.extend({}, options, {unset: true}));
362
382
  },
363
383
 
364
- // Clear all attributes on the model, firing `"change"` unless you choose
365
- // to silence it.
384
+ // Clear all attributes on the model, firing `"change"`.
366
385
  clear: function(options) {
367
386
  var attrs = {};
368
387
  for (var key in this.attributes) attrs[key] = void 0;
@@ -406,19 +425,20 @@
406
425
  return _.clone(this._previousAttributes);
407
426
  },
408
427
 
409
- // ---------------------------------------------------------------------
410
-
411
428
  // Fetch the model from the server. If the server's representation of the
412
- // model differs from its current attributes, they will be overriden,
429
+ // model differs from its current attributes, they will be overridden,
413
430
  // triggering a `"change"` event.
414
431
  fetch: function(options) {
415
432
  options = options ? _.clone(options) : {};
416
433
  if (options.parse === void 0) options.parse = true;
434
+ var model = this;
417
435
  var success = options.success;
418
- options.success = function(model, resp, options) {
436
+ options.success = function(resp) {
419
437
  if (!model.set(model.parse(resp, options), options)) return false;
420
438
  if (success) success(model, resp, options);
439
+ model.trigger('sync', model, resp, options);
421
440
  };
441
+ wrapError(this, options);
422
442
  return this.sync('read', this, options);
423
443
  },
424
444
 
@@ -426,7 +446,7 @@
426
446
  // If the server returns an attributes hash that differs, the model's
427
447
  // state will be `set` again.
428
448
  save: function(key, val, options) {
429
- var attrs, success, method, xhr, attributes = this.attributes;
449
+ var attrs, method, xhr, attributes = this.attributes;
430
450
 
431
451
  // Handle both `"key", value` and `{key: value}` -style arguments.
432
452
  if (key == null || typeof key === 'object') {
@@ -452,8 +472,9 @@
452
472
  // After a successful server-side save, the client is (optionally)
453
473
  // updated with the server-side state.
454
474
  if (options.parse === void 0) options.parse = true;
455
- success = options.success;
456
- options.success = function(model, resp, options) {
475
+ var model = this;
476
+ var success = options.success;
477
+ options.success = function(resp) {
457
478
  // Ensure attributes are restored during synchronous saves.
458
479
  model.attributes = attributes;
459
480
  var serverAttrs = model.parse(resp, options);
@@ -462,9 +483,10 @@
462
483
  return false;
463
484
  }
464
485
  if (success) success(model, resp, options);
486
+ model.trigger('sync', model, resp, options);
465
487
  };
488
+ wrapError(this, options);
466
489
 
467
- // Finish configuring and sending the Ajax request.
468
490
  method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
469
491
  if (method === 'patch') options.attrs = attrs;
470
492
  xhr = this.sync(method, this, options);
@@ -487,15 +509,17 @@
487
509
  model.trigger('destroy', model, model.collection, options);
488
510
  };
489
511
 
490
- options.success = function(model, resp, options) {
512
+ options.success = function(resp) {
491
513
  if (options.wait || model.isNew()) destroy();
492
514
  if (success) success(model, resp, options);
515
+ if (!model.isNew()) model.trigger('sync', model, resp, options);
493
516
  };
494
517
 
495
518
  if (this.isNew()) {
496
- options.success(this, null, options);
519
+ options.success();
497
520
  return false;
498
521
  }
522
+ wrapError(this, options);
499
523
 
500
524
  var xhr = this.sync('delete', this, options);
501
525
  if (!options.wait) destroy();
@@ -529,39 +553,61 @@
529
553
 
530
554
  // Check if the model is currently in a valid state.
531
555
  isValid: function(options) {
532
- return !this.validate || !this.validate(this.attributes, options);
556
+ return this._validate({}, _.extend(options || {}, { validate: true }));
533
557
  },
534
558
 
535
559
  // Run validation against the next complete set of model attributes,
536
- // returning `true` if all is well. Otherwise, fire a general
537
- // `"error"` event and call the error callback, if specified.
560
+ // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
538
561
  _validate: function(attrs, options) {
539
562
  if (!options.validate || !this.validate) return true;
540
563
  attrs = _.extend({}, this.attributes, attrs);
541
564
  var error = this.validationError = this.validate(attrs, options) || null;
542
565
  if (!error) return true;
543
- this.trigger('invalid', this, error, options || {});
566
+ this.trigger('invalid', this, error, _.extend(options || {}, {validationError: error}));
544
567
  return false;
545
568
  }
546
569
 
547
570
  });
548
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
+
549
584
  // Backbone.Collection
550
585
  // -------------------
551
586
 
552
- // Provides a standard collection class for our sets of models, ordered
553
- // 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
554
596
  // its models in sort order, as they're added and removed.
555
597
  var Collection = Backbone.Collection = function(models, options) {
556
598
  options || (options = {});
599
+ if (options.url) this.url = options.url;
557
600
  if (options.model) this.model = options.model;
558
601
  if (options.comparator !== void 0) this.comparator = options.comparator;
559
- this.models = [];
560
602
  this._reset();
561
603
  this.initialize.apply(this, arguments);
562
604
  if (models) this.reset(models, _.extend({silent: true}, options));
563
605
  };
564
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
+
565
611
  // Define the Collection's inheritable methods.
566
612
  _.extend(Collection.prototype, Events, {
567
613
 
@@ -586,88 +632,118 @@
586
632
 
587
633
  // Add a model, or list of models to the set.
588
634
  add: function(models, options) {
635
+ return this.set(models, _.defaults(options || {}, addOptions));
636
+ },
637
+
638
+ // Remove a model, or a list of models from the set.
639
+ remove: function(models, options) {
589
640
  models = _.isArray(models) ? models.slice() : [models];
590
641
  options || (options = {});
591
- var i, l, model, attrs, existing, doSort, add, at, sort, sortAttr;
592
- add = [];
593
- at = options.at;
594
- sort = this.comparator && (at == null) && options.sort != false;
595
- sortAttr = _.isString(this.comparator) ? this.comparator : null;
642
+ var i, l, index, model;
643
+ for (i = 0, l = models.length; i < l; i++) {
644
+ model = this.get(models[i]);
645
+ if (!model) continue;
646
+ delete this._byId[model.id];
647
+ delete this._byId[model.cid];
648
+ index = this.indexOf(model);
649
+ this.models.splice(index, 1);
650
+ this.length--;
651
+ if (!options.silent) {
652
+ options.index = index;
653
+ model.trigger('remove', model, this, options);
654
+ }
655
+ this._removeReference(model);
656
+ }
657
+ return this;
658
+ },
659
+
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 = {};
596
673
 
597
674
  // Turn bare objects into model references, and prevent invalid models
598
675
  // from being added.
599
676
  for (i = 0, l = models.length; i < l; i++) {
600
- if (!(model = this._prepareModel(attrs = models[i], options))) {
601
- this.trigger('invalid', this, attrs, options);
602
- continue;
603
- }
677
+ if (!(model = this._prepareModel(models[i], options))) continue;
604
678
 
605
679
  // If a duplicate is found, prevent it from being added and
606
680
  // optionally merge it into the existing model.
607
681
  if (existing = this.get(model)) {
682
+ if (options.remove) modelMap[existing.cid] = true;
608
683
  if (options.merge) {
609
- existing.set(attrs === model ? model.attributes : attrs, options);
610
- if (sort && !doSort && existing.hasChanged(sortAttr)) doSort = true;
684
+ existing.set(model.attributes, options);
685
+ if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
611
686
  }
612
- continue;
613
- }
614
687
 
615
- // This is a new model, push it to the `add` list.
616
- add.push(model);
688
+ // This is a new model, push it to the `toAdd` list.
689
+ } else if (options.add) {
690
+ toAdd.push(model);
617
691
 
618
- // Listen to added models' events, and index models for lookup by
619
- // `id` and by `cid`.
620
- model.on('all', this._onModelEvent, this);
621
- this._byId[model.cid] = model;
622
- if (model.id != null) this._byId[model.id] = model;
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);
623
706
  }
624
707
 
625
708
  // See if sorting is needed, update `length` and splice in new models.
626
- if (add.length) {
627
- if (sort) doSort = true;
628
- this.length += add.length;
709
+ if (toAdd.length) {
710
+ if (sortable) sort = true;
711
+ this.length += toAdd.length;
629
712
  if (at != null) {
630
- splice.apply(this.models, [at, 0].concat(add));
713
+ splice.apply(this.models, [at, 0].concat(toAdd));
631
714
  } else {
632
- push.apply(this.models, add);
715
+ push.apply(this.models, toAdd);
633
716
  }
634
717
  }
635
718
 
636
719
  // Silently sort the collection if appropriate.
637
- if (doSort) this.sort({silent: true});
720
+ if (sort) this.sort({silent: true});
638
721
 
639
722
  if (options.silent) return this;
640
723
 
641
724
  // Trigger `add` events.
642
- for (i = 0, l = add.length; i < l; i++) {
643
- (model = add[i]).trigger('add', model, this, options);
725
+ for (i = 0, l = toAdd.length; i < l; i++) {
726
+ (model = toAdd[i]).trigger('add', model, this, options);
644
727
  }
645
728
 
646
729
  // Trigger `sort` if the collection was sorted.
647
- if (doSort) this.trigger('sort', this, options);
648
-
730
+ if (sort) this.trigger('sort', this, options);
649
731
  return this;
650
732
  },
651
733
 
652
- // Remove a model, or a list of models from the set.
653
- remove: function(models, options) {
654
- models = _.isArray(models) ? models.slice() : [models];
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) {
655
739
  options || (options = {});
656
- var i, l, index, model;
657
- for (i = 0, l = models.length; i < l; i++) {
658
- model = this.get(models[i]);
659
- if (!model) continue;
660
- delete this._byId[model.id];
661
- delete this._byId[model.cid];
662
- index = this.indexOf(model);
663
- this.models.splice(index, 1);
664
- this.length--;
665
- if (!options.silent) {
666
- options.index = index;
667
- model.trigger('remove', model, this, options);
668
- }
669
- this._removeReference(model);
740
+ for (var i = 0, l = this.models.length; i < l; i++) {
741
+ this._removeReference(this.models[i]);
670
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);
671
747
  return this;
672
748
  },
673
749
 
@@ -707,8 +783,7 @@
707
783
  // Get a model from the set by id.
708
784
  get: function(obj) {
709
785
  if (obj == null) return void 0;
710
- this._idAttr || (this._idAttr = this.model.prototype.idAttribute);
711
- return this._byId[obj.id || obj.cid || obj[this._idAttr] || obj];
786
+ return this._byId[obj.id != null ? obj.id : obj.cid || obj];
712
787
  },
713
788
 
714
789
  // Get the model at the given index.
@@ -716,10 +791,11 @@
716
791
  return this.models[index];
717
792
  },
718
793
 
719
- // Return models with matching attributes. Useful for simple cases of `filter`.
720
- where: function(attrs) {
721
- if (_.isEmpty(attrs)) return [];
722
- return this.filter(function(model) {
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) {
723
799
  for (var key in attrs) {
724
800
  if (attrs[key] !== model.get(key)) return false;
725
801
  }
@@ -727,13 +803,17 @@
727
803
  });
728
804
  },
729
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
+
730
812
  // Force the collection to re-sort itself. You don't need to call this under
731
813
  // normal circumstances, as the set will maintain sort order as each item
732
814
  // is added.
733
815
  sort: function(options) {
734
- if (!this.comparator) {
735
- throw new Error('Cannot sort a set without a comparator');
736
- }
816
+ if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
737
817
  options || (options = {});
738
818
 
739
819
  // Run sort based on type of `comparator`.
@@ -747,75 +827,36 @@
747
827
  return this;
748
828
  },
749
829
 
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);
838
+ },
839
+
750
840
  // Pluck an attribute from each model in the collection.
751
841
  pluck: function(attr) {
752
842
  return _.invoke(this.models, 'get', attr);
753
843
  },
754
844
 
755
- // Smartly update a collection with a change set of models, adding,
756
- // removing, and merging as necessary.
757
- update: function(models, options) {
758
- options = _.extend({add: true, merge: true, remove: true}, options);
759
- if (options.parse) models = this.parse(models, options);
760
- var model, i, l, existing;
761
- var add = [], remove = [], modelMap = {};
762
-
763
- // Allow a single model (or no argument) to be passed.
764
- if (!_.isArray(models)) models = models ? [models] : [];
765
-
766
- // Proxy to `add` for this case, no need to iterate...
767
- if (options.add && !options.remove) return this.add(models, options);
768
-
769
- // Determine which models to add and merge, and which to remove.
770
- for (i = 0, l = models.length; i < l; i++) {
771
- model = models[i];
772
- existing = this.get(model);
773
- if (options.remove && existing) modelMap[existing.cid] = true;
774
- if ((options.add && !existing) || (options.merge && existing)) {
775
- add.push(model);
776
- }
777
- }
778
- if (options.remove) {
779
- for (i = 0, l = this.models.length; i < l; i++) {
780
- model = this.models[i];
781
- if (!modelMap[model.cid]) remove.push(model);
782
- }
783
- }
784
-
785
- // Remove models (if applicable) before we add and merge the rest.
786
- if (remove.length) this.remove(remove, options);
787
- if (add.length) this.add(add, options);
788
- return this;
789
- },
790
-
791
- // When you have more items than you want to add or remove individually,
792
- // you can reset the entire set with a new list of models, without firing
793
- // any `add` or `remove` events. Fires `reset` when finished.
794
- reset: function(models, options) {
795
- options || (options = {});
796
- if (options.parse) models = this.parse(models, options);
797
- for (var i = 0, l = this.models.length; i < l; i++) {
798
- this._removeReference(this.models[i]);
799
- }
800
- options.previousModels = this.models.slice();
801
- this._reset();
802
- if (models) this.add(models, _.extend({silent: true}, options));
803
- if (!options.silent) this.trigger('reset', this, options);
804
- return this;
805
- },
806
-
807
845
  // Fetch the default set of models for this collection, resetting the
808
- // collection when they arrive. If `update: true` is passed, the response
809
- // data will be passed through the `update` method instead of `reset`.
846
+ // collection when they arrive. If `reset: true` is passed, the response
847
+ // data will be passed through the `reset` method instead of `set`.
810
848
  fetch: function(options) {
811
849
  options = options ? _.clone(options) : {};
812
850
  if (options.parse === void 0) options.parse = true;
813
851
  var success = options.success;
814
- options.success = function(collection, resp, options) {
815
- var method = options.update ? 'update' : 'reset';
852
+ var collection = this;
853
+ options.success = function(resp) {
854
+ var method = options.reset ? 'reset' : 'set';
816
855
  collection[method](resp, options);
817
856
  if (success) success(collection, resp, options);
857
+ collection.trigger('sync', collection, resp, options);
818
858
  };
859
+ wrapError(this, options);
819
860
  return this.sync('read', this, options);
820
861
  },
821
862
 
@@ -828,7 +869,7 @@
828
869
  if (!options.wait) this.add(model, options);
829
870
  var collection = this;
830
871
  var success = options.success;
831
- options.success = function(model, resp, options) {
872
+ options.success = function(resp) {
832
873
  if (options.wait) collection.add(model, options);
833
874
  if (success) success(model, resp, options);
834
875
  };
@@ -847,14 +888,16 @@
847
888
  return new this.constructor(this.models);
848
889
  },
849
890
 
850
- // Reset all internal state. Called when the collection is reset.
891
+ // Private method to reset all internal state. Called when the collection
892
+ // is first initialized or reset.
851
893
  _reset: function() {
852
894
  this.length = 0;
853
- this.models.length = 0;
895
+ this.models = [];
854
896
  this._byId = {};
855
897
  },
856
898
 
857
- // Prepare a model or hash of attributes to be added to this collection.
899
+ // Prepare a hash of attributes (or other model) to be added to this
900
+ // collection.
858
901
  _prepareModel: function(attrs, options) {
859
902
  if (attrs instanceof Model) {
860
903
  if (!attrs.collection) attrs.collection = this;
@@ -863,11 +906,14 @@
863
906
  options || (options = {});
864
907
  options.collection = this;
865
908
  var model = new this.model(attrs, options);
866
- if (!model._validate(attrs, options)) return false;
909
+ if (!model._validate(attrs, options)) {
910
+ this.trigger('invalid', this, attrs, options);
911
+ return false;
912
+ }
867
913
  return model;
868
914
  },
869
915
 
870
- // Internal method to remove a model's ties to a collection.
916
+ // Internal method to sever a model's ties to a collection.
871
917
  _removeReference: function(model) {
872
918
  if (this === model.collection) delete model.collection;
873
919
  model.off('all', this._onModelEvent, this);
@@ -885,19 +931,13 @@
885
931
  if (model.id != null) this._byId[model.id] = model;
886
932
  }
887
933
  this.trigger.apply(this, arguments);
888
- },
889
-
890
- sortedIndex: function (model, value, context) {
891
- value || (value = this.comparator);
892
- var iterator = _.isFunction(value) ? value : function(model) {
893
- return model.get(value);
894
- };
895
- return _.sortedIndex(this.models, model, iterator, context);
896
934
  }
897
935
 
898
936
  });
899
937
 
900
938
  // Underscore methods that we want to implement on the Collection.
939
+ // 90% of the core usefulness of Backbone Collections is actually implemented
940
+ // right here:
901
941
  var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
902
942
  'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
903
943
  'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
@@ -927,62 +967,303 @@
927
967
  };
928
968
  });
929
969
 
930
- // Backbone.Router
931
- // ---------------
970
+ // Backbone.View
971
+ // -------------
932
972
 
933
- // Routers map faux-URLs to actions, and fire events when routes are
934
- // matched. Creating a new one sets its `routes` hash, if not set statically.
935
- var Router = Backbone.Router = function(options) {
936
- options || (options = {});
937
- if (options.routes) this.routes = options.routes;
938
- this._bindRoutes();
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();
939
987
  this.initialize.apply(this, arguments);
988
+ this.delegateEvents();
940
989
  };
941
990
 
942
- // Cached regular expressions for matching named param parts and splatted
943
- // parts of route strings.
944
- var optionalParam = /\((.*?)\)/g;
945
- var namedParam = /(\(\?)?:\w+/g;
946
- var splatParam = /\*\w+/g;
947
- var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
991
+ // Cached regex to split keys for `delegate`.
992
+ var delegateEventSplitter = /^(\S+)\s*(.*)$/;
948
993
 
949
- // Set up all inheritable **Backbone.Router** properties and methods.
950
- _.extend(Router.prototype, Events, {
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
+ },
951
1008
 
952
1009
  // Initialize is an empty function by default. Override it with your own
953
1010
  // initialization logic.
954
1011
  initialize: function(){},
955
1012
 
956
- // Manually bind a single named route to a callback. For example:
957
- //
958
- // this.route('search/:query/p:num', 'search', function(query, num) {
959
- // ...
960
- // });
961
- //
962
- route: function(route, name, callback) {
963
- if (!_.isRegExp(route)) route = this._routeToRegExp(route);
964
- if (!callback) callback = this[name];
965
- Backbone.history.route(route, _.bind(function(fragment) {
966
- var args = this._extractParameters(route, fragment);
967
- callback && callback.apply(this, args);
968
- this.trigger.apply(this, ['route:' + name].concat(args));
969
- this.trigger('route', name, args);
970
- Backbone.history.trigger('route', this, name, args);
971
- }, this));
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() {
972
1017
  return this;
973
1018
  },
974
1019
 
975
- // Simple proxy to `Backbone.history` to save a fragment into the history.
976
- navigate: function(fragment, options) {
977
- Backbone.history.navigate(fragment, options);
978
- return this;
979
- },
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
+
1205
+ // Backbone.Router
1206
+ // ---------------
1207
+
1208
+ // Routers map faux-URLs to actions, and fire events when routes are
1209
+ // matched. Creating a new one sets its `routes` hash, if not set statically.
1210
+ var Router = Backbone.Router = function(options) {
1211
+ options || (options = {});
1212
+ if (options.routes) this.routes = options.routes;
1213
+ this._bindRoutes();
1214
+ this.initialize.apply(this, arguments);
1215
+ };
1216
+
1217
+ // Cached regular expressions for matching named param parts and splatted
1218
+ // parts of route strings.
1219
+ var optionalParam = /\((.*?)\)/g;
1220
+ var namedParam = /(\(\?)?:\w+/g;
1221
+ var splatParam = /\*\w+/g;
1222
+ var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
1223
+
1224
+ // Set up all inheritable **Backbone.Router** properties and methods.
1225
+ _.extend(Router.prototype, Events, {
1226
+
1227
+ // Initialize is an empty function by default. Override it with your own
1228
+ // initialization logic.
1229
+ initialize: function(){},
1230
+
1231
+ // Manually bind a single named route to a callback. For example:
1232
+ //
1233
+ // this.route('search/:query/p:num', 'search', function(query, num) {
1234
+ // ...
1235
+ // });
1236
+ //
1237
+ route: function(route, name, callback) {
1238
+ if (!_.isRegExp(route)) route = this._routeToRegExp(route);
1239
+ if (_.isFunction(name)) {
1240
+ callback = name;
1241
+ name = '';
1242
+ }
1243
+ if (!callback) callback = this[name];
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
+ });
1252
+ return this;
1253
+ },
1254
+
1255
+ // Simple proxy to `Backbone.history` to save a fragment into the history.
1256
+ navigate: function(fragment, options) {
1257
+ Backbone.history.navigate(fragment, options);
1258
+ return this;
1259
+ },
980
1260
 
981
1261
  // Bind all defined routes to `Backbone.history`. We have to reverse the
982
1262
  // order of the routes here to support behavior where the most general
983
1263
  // routes can be defined at the bottom of the route map.
984
1264
  _bindRoutes: function() {
985
1265
  if (!this.routes) return;
1266
+ this.routes = _.result(this, 'routes');
986
1267
  var route, routes = _.keys(this.routes);
987
1268
  while ((route = routes.pop()) != null) {
988
1269
  this.route(route, this.routes[route]);
@@ -1002,9 +1283,13 @@
1002
1283
  },
1003
1284
 
1004
1285
  // Given a route, and a URL fragment that it matches, return the array of
1005
- // extracted parameters.
1286
+ // extracted decoded parameters. Empty or unmatched parameters will be
1287
+ // treated as `null` to normalize cross-browser behavior.
1006
1288
  _extractParameters: function(route, fragment) {
1007
- 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
+ });
1008
1293
  }
1009
1294
 
1010
1295
  });
@@ -1012,8 +1297,11 @@
1012
1297
  // Backbone.History
1013
1298
  // ----------------
1014
1299
 
1015
- // Handles cross-browser history management, based on URL fragments. If the
1016
- // browser does not support `onhashchange`, falls back to polling.
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.
1017
1305
  var History = Backbone.History = function() {
1018
1306
  this.handlers = [];
1019
1307
  _.bindAll(this, 'checkUrl');
@@ -1123,330 +1411,106 @@
1123
1411
  } else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
1124
1412
  this.fragment = this.getHash().replace(routeStripper, '');
1125
1413
  this.history.replaceState({}, document.title, this.root + this.fragment + loc.search);
1126
- }
1127
-
1128
- if (!this.options.silent) return this.loadUrl();
1129
- },
1130
-
1131
- // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
1132
- // but possibly useful for unit testing Routers.
1133
- stop: function() {
1134
- Backbone.$(window).off('popstate', this.checkUrl).off('hashchange', this.checkUrl);
1135
- clearInterval(this._checkUrlInterval);
1136
- History.started = false;
1137
- },
1138
-
1139
- // Add a route to be tested when the fragment changes. Routes added later
1140
- // may override previous routes.
1141
- route: function(route, callback) {
1142
- this.handlers.unshift({route: route, callback: callback});
1143
- },
1144
-
1145
- // Checks the current URL to see if it has changed, and if it has,
1146
- // calls `loadUrl`, normalizing across the hidden iframe.
1147
- checkUrl: function(e) {
1148
- var current = this.getFragment();
1149
- if (current === this.fragment && this.iframe) {
1150
- current = this.getFragment(this.getHash(this.iframe));
1151
- }
1152
- if (current === this.fragment) return false;
1153
- if (this.iframe) this.navigate(current);
1154
- this.loadUrl() || this.loadUrl(this.getHash());
1155
- },
1156
-
1157
- // Attempt to load the current URL fragment. If a route succeeds with a
1158
- // match, returns `true`. If no defined routes matches the fragment,
1159
- // returns `false`.
1160
- loadUrl: function(fragmentOverride) {
1161
- var fragment = this.fragment = this.getFragment(fragmentOverride);
1162
- var matched = _.any(this.handlers, function(handler) {
1163
- if (handler.route.test(fragment)) {
1164
- handler.callback(fragment);
1165
- return true;
1166
- }
1167
- });
1168
- return matched;
1169
- },
1170
-
1171
- // Save a fragment into the hash history, or replace the URL state if the
1172
- // 'replace' option is passed. You are responsible for properly URL-encoding
1173
- // the fragment in advance.
1174
- //
1175
- // The options object can contain `trigger: true` if you wish to have the
1176
- // route callback be fired (not usually desirable), or `replace: true`, if
1177
- // you wish to modify the current URL without adding an entry to the history.
1178
- navigate: function(fragment, options) {
1179
- if (!History.started) return false;
1180
- if (!options || options === true) options = {trigger: options};
1181
- fragment = this.getFragment(fragment || '');
1182
- if (this.fragment === fragment) return;
1183
- this.fragment = fragment;
1184
- var url = this.root + fragment;
1185
-
1186
- // If pushState is available, we use it to set the fragment as a real URL.
1187
- if (this._hasPushState) {
1188
- this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
1189
-
1190
- // If hash changes haven't been explicitly disabled, update the hash
1191
- // fragment to store history.
1192
- } else if (this._wantsHashChange) {
1193
- this._updateHash(this.location, fragment, options.replace);
1194
- if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) {
1195
- // Opening and closing the iframe tricks IE7 and earlier to push a
1196
- // history entry on hash-tag change. When replace is true, we don't
1197
- // want this.
1198
- if(!options.replace) this.iframe.document.open().close();
1199
- this._updateHash(this.iframe.location, fragment, options.replace);
1200
- }
1201
-
1202
- // If you've told us that you explicitly don't want fallback hashchange-
1203
- // based history, then `navigate` becomes a page refresh.
1204
- } else {
1205
- return this.location.assign(url);
1206
- }
1207
- if (options.trigger) this.loadUrl(fragment);
1208
- },
1209
-
1210
- // Update the hash location, either replacing the current entry, or adding
1211
- // a new one to the browser history.
1212
- _updateHash: function(location, fragment, replace) {
1213
- if (replace) {
1214
- var href = location.href.replace(/(javascript:|#).*$/, '');
1215
- location.replace(href + '#' + fragment);
1216
- } else {
1217
- // Some browsers require that `hash` contains a leading #.
1218
- location.hash = '#' + fragment;
1219
- }
1220
- }
1221
-
1222
- });
1223
-
1224
- // Create the default Backbone.history.
1225
- Backbone.history = new History;
1226
-
1227
- // Backbone.View
1228
- // -------------
1229
-
1230
- // Creating a Backbone.View creates its initial element outside of the DOM,
1231
- // if an existing element is not provided...
1232
- var View = Backbone.View = function(options) {
1233
- this.cid = _.uniqueId('view');
1234
- this._configure(options || {});
1235
- this._ensureElement();
1236
- this.initialize.apply(this, arguments);
1237
- this.delegateEvents();
1238
- };
1239
-
1240
- // Cached regex to split keys for `delegate`.
1241
- var delegateEventSplitter = /^(\S+)\s*(.*)$/;
1242
-
1243
- // List of view options to be merged as properties.
1244
- var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
1245
-
1246
- // Set up all inheritable **Backbone.View** properties and methods.
1247
- _.extend(View.prototype, Events, {
1248
-
1249
- // The default `tagName` of a View's element is `"div"`.
1250
- tagName: 'div',
1251
-
1252
- // jQuery delegate for element lookup, scoped to DOM elements within the
1253
- // current view. This should be prefered to global lookups where possible.
1254
- $: function(selector) {
1255
- return this.$el.find(selector);
1256
- },
1257
-
1258
- // Initialize is an empty function by default. Override it with your own
1259
- // initialization logic.
1260
- initialize: function(){},
1261
-
1262
- // **render** is the core function that your view should override, in order
1263
- // to populate its element (`this.el`), with the appropriate HTML. The
1264
- // convention is for **render** to always return `this`.
1265
- render: function() {
1266
- return this;
1267
- },
1268
-
1269
- // Remove this view by taking the element out of the DOM, and removing any
1270
- // applicable Backbone.Events listeners.
1271
- remove: function() {
1272
- this.$el.remove();
1273
- this.stopListening();
1274
- return this;
1275
- },
1276
-
1277
- // Change the view's element (`this.el` property), including event
1278
- // re-delegation.
1279
- setElement: function(element, delegate) {
1280
- if (this.$el) this.undelegateEvents();
1281
- this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
1282
- this.el = this.$el[0];
1283
- if (delegate !== false) this.delegateEvents();
1284
- return this;
1285
- },
1286
-
1287
- // Set callbacks, where `this.events` is a hash of
1288
- //
1289
- // *{"event selector": "callback"}*
1290
- //
1291
- // {
1292
- // 'mousedown .title': 'edit',
1293
- // 'click .button': 'save'
1294
- // 'click .open': function(e) { ... }
1295
- // }
1296
- //
1297
- // pairs. Callbacks will be bound to the view, with `this` set properly.
1298
- // Uses event delegation for efficiency.
1299
- // Omitting the selector binds the event to `this.el`.
1300
- // This only works for delegate-able events: not `focus`, `blur`, and
1301
- // not `change`, `submit`, and `reset` in Internet Explorer.
1302
- delegateEvents: function(events) {
1303
- if (!(events || (events = _.result(this, 'events')))) return;
1304
- this.undelegateEvents();
1305
- for (var key in events) {
1306
- var method = events[key];
1307
- if (!_.isFunction(method)) method = this[events[key]];
1308
- if (!method) throw new Error('Method "' + events[key] + '" does not exist');
1309
- var match = key.match(delegateEventSplitter);
1310
- var eventName = match[1], selector = match[2];
1311
- method = _.bind(method, this);
1312
- eventName += '.delegateEvents' + this.cid;
1313
- if (selector === '') {
1314
- this.$el.on(eventName, method);
1315
- } else {
1316
- this.$el.on(eventName, selector, method);
1317
- }
1318
- }
1319
- },
1320
-
1321
- // Clears all callbacks previously bound to the view with `delegateEvents`.
1322
- // You usually don't need to use this, but may wish to if you have multiple
1323
- // Backbone views attached to the same DOM element.
1324
- undelegateEvents: function() {
1325
- this.$el.off('.delegateEvents' + this.cid);
1326
- },
1327
-
1328
- // Performs the initial configuration of a View with a set of options.
1329
- // Keys with special meaning *(model, collection, id, className)*, are
1330
- // attached directly to the view.
1331
- _configure: function(options) {
1332
- if (this.options) options = _.extend({}, _.result(this, 'options'), options);
1333
- _.extend(this, _.pick(options, viewOptions));
1334
- this.options = options;
1335
- },
1336
-
1337
- // Ensure that the View has a DOM element to render into.
1338
- // If `this.el` is a string, pass it through `$()`, take the first
1339
- // matching element, and re-assign it to `el`. Otherwise, create
1340
- // an element from the `id`, `className` and `tagName` properties.
1341
- _ensureElement: function() {
1342
- if (!this.el) {
1343
- var attrs = _.extend({}, _.result(this, 'attributes'));
1344
- if (this.id) attrs.id = _.result(this, 'id');
1345
- if (this.className) attrs['class'] = _.result(this, 'className');
1346
- var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
1347
- this.setElement($el, false);
1348
- } else {
1349
- this.setElement(_.result(this, 'el'), false);
1350
- }
1351
- }
1352
-
1353
- });
1354
-
1355
- // Backbone.sync
1356
- // -------------
1357
-
1358
- // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
1359
- var methodMap = {
1360
- 'create': 'POST',
1361
- 'update': 'PUT',
1362
- 'patch': 'PATCH',
1363
- 'delete': 'DELETE',
1364
- 'read': 'GET'
1365
- };
1414
+ }
1366
1415
 
1367
- // Override this function to change the manner in which Backbone persists
1368
- // models to the server. You will be passed the type of request, and the
1369
- // model in question. By default, makes a RESTful Ajax request
1370
- // to the model's `url()`. Some possible customizations could be:
1371
- //
1372
- // * Use `setTimeout` to batch rapid-fire updates into a single request.
1373
- // * Send up the models as XML instead of JSON.
1374
- // * Persist models via WebSockets instead of Ajax.
1375
- //
1376
- // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
1377
- // as `POST`, with a `_method` parameter containing the true HTTP method,
1378
- // as well as all requests with the body as `application/x-www-form-urlencoded`
1379
- // instead of `application/json` with the model in a param named `model`.
1380
- // Useful when interfacing with server-side languages like **PHP** that make
1381
- // it difficult to read the body of `PUT` requests.
1382
- Backbone.sync = function(method, model, options) {
1383
- var type = methodMap[method];
1416
+ if (!this.options.silent) return this.loadUrl();
1417
+ },
1384
1418
 
1385
- // Default options, unless specified.
1386
- _.defaults(options || (options = {}), {
1387
- emulateHTTP: Backbone.emulateHTTP,
1388
- emulateJSON: Backbone.emulateJSON
1389
- });
1419
+ // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
1420
+ // but possibly useful for unit testing Routers.
1421
+ stop: function() {
1422
+ Backbone.$(window).off('popstate', this.checkUrl).off('hashchange', this.checkUrl);
1423
+ clearInterval(this._checkUrlInterval);
1424
+ History.started = false;
1425
+ },
1390
1426
 
1391
- // Default JSON-request options.
1392
- var params = {type: type, dataType: 'json'};
1427
+ // Add a route to be tested when the fragment changes. Routes added later
1428
+ // may override previous routes.
1429
+ route: function(route, callback) {
1430
+ this.handlers.unshift({route: route, callback: callback});
1431
+ },
1393
1432
 
1394
- // Ensure that we have a URL.
1395
- if (!options.url) {
1396
- params.url = _.result(model, 'url') || urlError();
1397
- }
1433
+ // Checks the current URL to see if it has changed, and if it has,
1434
+ // calls `loadUrl`, normalizing across the hidden iframe.
1435
+ checkUrl: function(e) {
1436
+ var current = this.getFragment();
1437
+ if (current === this.fragment && this.iframe) {
1438
+ current = this.getFragment(this.getHash(this.iframe));
1439
+ }
1440
+ if (current === this.fragment) return false;
1441
+ if (this.iframe) this.navigate(current);
1442
+ this.loadUrl() || this.loadUrl(this.getHash());
1443
+ },
1398
1444
 
1399
- // Ensure that we have the appropriate request data.
1400
- if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
1401
- params.contentType = 'application/json';
1402
- params.data = JSON.stringify(options.attrs || model.toJSON(options));
1403
- }
1445
+ // Attempt to load the current URL fragment. If a route succeeds with a
1446
+ // match, returns `true`. If no defined routes matches the fragment,
1447
+ // returns `false`.
1448
+ loadUrl: function(fragmentOverride) {
1449
+ var fragment = this.fragment = this.getFragment(fragmentOverride);
1450
+ var matched = _.any(this.handlers, function(handler) {
1451
+ if (handler.route.test(fragment)) {
1452
+ handler.callback(fragment);
1453
+ return true;
1454
+ }
1455
+ });
1456
+ return matched;
1457
+ },
1404
1458
 
1405
- // For older servers, emulate JSON by encoding the request into an HTML-form.
1406
- if (options.emulateJSON) {
1407
- params.contentType = 'application/x-www-form-urlencoded';
1408
- params.data = params.data ? {model: params.data} : {};
1409
- }
1459
+ // Save a fragment into the hash history, or replace the URL state if the
1460
+ // 'replace' option is passed. You are responsible for properly URL-encoding
1461
+ // the fragment in advance.
1462
+ //
1463
+ // The options object can contain `trigger: true` if you wish to have the
1464
+ // route callback be fired (not usually desirable), or `replace: true`, if
1465
+ // you wish to modify the current URL without adding an entry to the history.
1466
+ navigate: function(fragment, options) {
1467
+ if (!History.started) return false;
1468
+ if (!options || options === true) options = {trigger: options};
1469
+ fragment = this.getFragment(fragment || '');
1470
+ if (this.fragment === fragment) return;
1471
+ this.fragment = fragment;
1472
+ var url = this.root + fragment;
1410
1473
 
1411
- // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
1412
- // And an `X-HTTP-Method-Override` header.
1413
- if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
1414
- params.type = 'POST';
1415
- if (options.emulateJSON) params.data._method = type;
1416
- var beforeSend = options.beforeSend;
1417
- options.beforeSend = function(xhr) {
1418
- xhr.setRequestHeader('X-HTTP-Method-Override', type);
1419
- if (beforeSend) return beforeSend.apply(this, arguments);
1420
- };
1421
- }
1474
+ // If pushState is available, we use it to set the fragment as a real URL.
1475
+ if (this._hasPushState) {
1476
+ this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
1422
1477
 
1423
- // Don't process data on a non-GET request.
1424
- if (params.type !== 'GET' && !options.emulateJSON) {
1425
- params.processData = false;
1426
- }
1478
+ // If hash changes haven't been explicitly disabled, update the hash
1479
+ // fragment to store history.
1480
+ } else if (this._wantsHashChange) {
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.
1486
+ if(!options.replace) this.iframe.document.open().close();
1487
+ this._updateHash(this.iframe.location, fragment, options.replace);
1488
+ }
1427
1489
 
1428
- var success = options.success;
1429
- options.success = function(resp) {
1430
- if (success) success(model, resp, options);
1431
- model.trigger('sync', model, resp, options);
1432
- };
1490
+ // If you've told us that you explicitly don't want fallback hashchange-
1491
+ // based history, then `navigate` becomes a page refresh.
1492
+ } else {
1493
+ return this.location.assign(url);
1494
+ }
1495
+ if (options.trigger) this.loadUrl(fragment);
1496
+ },
1433
1497
 
1434
- var error = options.error;
1435
- options.error = function(xhr) {
1436
- if (error) error(model, xhr, options);
1437
- model.trigger('error', model, xhr, options);
1438
- };
1498
+ // Update the hash location, either replacing the current entry, or adding
1499
+ // a new one to the browser history.
1500
+ _updateHash: function(location, fragment, replace) {
1501
+ if (replace) {
1502
+ var href = location.href.replace(/(javascript:|#).*$/, '');
1503
+ location.replace(href + '#' + fragment);
1504
+ } else {
1505
+ // Some browsers require that `hash` contains a leading #.
1506
+ location.hash = '#' + fragment;
1507
+ }
1508
+ }
1439
1509
 
1440
- // Make the request, allowing the user to override any Ajax options.
1441
- var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
1442
- model.trigger('request', model, xhr, options);
1443
- return xhr;
1444
- };
1510
+ });
1445
1511
 
1446
- // Set the default implementation of `Backbone.ajax` to proxy through to `$`.
1447
- Backbone.ajax = function() {
1448
- return Backbone.$.ajax.apply(Backbone.$, arguments);
1449
- };
1512
+ // Create the default Backbone.history.
1513
+ Backbone.history = new History;
1450
1514
 
1451
1515
  // Helpers
1452
1516
  // -------
@@ -1495,12 +1559,26 @@
1495
1559
  throw new Error('A "url" property or function must be specified');
1496
1560
  };
1497
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
+
1498
1571
  }).call(this);
1499
1572
 
1500
- // Backbone.BabySitter, v0.0.4
1501
- // Copyright (c)2012 Derick Bailey, Muted Solutions, LLC.
1573
+ // Backbone.BabySitter
1574
+ // -------------------
1575
+ // v0.0.5
1576
+ //
1577
+ // Copyright (c)2013 Derick Bailey, Muted Solutions, LLC.
1502
1578
  // Distributed under MIT license
1503
- // http://github.com/marionettejs/backbone.babysitter
1579
+ //
1580
+ // http://github.com/babysitterjs/backbone.babysitter
1581
+
1504
1582
  // Backbone.ChildViewContainer
1505
1583
  // ---------------------------
1506
1584
  //
@@ -1690,151 +1768,298 @@ Backbone.ChildViewContainer = (function(Backbone, _){
1690
1768
  // return the public API
1691
1769
  return Container;
1692
1770
  })(Backbone, _);
1693
- // Backbone.Wreqr, v0.1.1
1771
+
1772
+ // Backbone.Wreqr (Backbone.Marionette)
1773
+ // ----------------------------------
1774
+ // v0.2.0
1775
+ //
1694
1776
  // Copyright (c)2013 Derick Bailey, Muted Solutions, LLC.
1695
1777
  // Distributed under MIT license
1778
+ //
1696
1779
  // http://github.com/marionettejs/backbone.wreqr
1780
+
1781
+
1697
1782
  Backbone.Wreqr = (function(Backbone, Marionette, _){
1698
1783
  "use strict";
1699
1784
  var Wreqr = {};
1700
1785
 
1701
1786
  // Handlers
1702
- // --------
1703
- // A registry of functions to call, given a name
1787
+ // --------
1788
+ // A registry of functions to call, given a name
1789
+
1790
+ Wreqr.Handlers = (function(Backbone, _){
1791
+ "use strict";
1704
1792
 
1705
- Wreqr.Handlers = (function(Backbone, _){
1706
- "use strict";
1793
+ // Constructor
1794
+ // -----------
1795
+
1796
+ var Handlers = function(options){
1797
+ this.options = options;
1798
+ this._wreqrHandlers = {};
1707
1799
 
1708
- // Constructor
1709
- // -----------
1710
-
1711
- var Handlers = function(){
1712
- this._handlers = {};
1713
- };
1714
-
1715
- Handlers.extend = Backbone.Model.extend;
1716
-
1717
- // Instance Members
1718
- // ----------------
1719
-
1720
- _.extend(Handlers.prototype, {
1721
-
1722
- // Add a handler for the given name, with an
1723
- // optional context to run the handler within
1724
- addHandler: function(name, handler, context){
1725
- var config = {
1726
- callback: handler,
1727
- context: context
1728
- };
1729
-
1730
- this._handlers[name] = config;
1731
- },
1732
-
1733
- // Get the currently registered handler for
1734
- // the specified name. Throws an exception if
1735
- // no handler is found.
1736
- getHandler: function(name){
1737
- var config = this._handlers[name];
1738
-
1739
- if (!config){
1740
- throw new Error("Handler not found for '" + name + "'");
1800
+ if (_.isFunction(this.initialize)){
1801
+ this.initialize(options);
1802
+ }
1803
+ };
1804
+
1805
+ Handlers.extend = Backbone.Model.extend;
1806
+
1807
+ // Instance Members
1808
+ // ----------------
1809
+
1810
+ _.extend(Handlers.prototype, Backbone.Events, {
1811
+
1812
+ // Add multiple handlers using an object literal configuration
1813
+ setHandlers: function(handlers){
1814
+ _.each(handlers, function(handler, name){
1815
+ var context = null;
1816
+
1817
+ if (_.isObject(handler) && !_.isFunction(handler)){
1818
+ context = handler.context;
1819
+ handler = handler.callback;
1741
1820
  }
1742
-
1743
- return function(){
1744
- var args = Array.prototype.slice.apply(arguments);
1745
- return config.callback.apply(config.context, args);
1821
+
1822
+ this.setHandler(name, handler, context);
1823
+ }, this);
1824
+ },
1825
+
1826
+ // Add a handler for the given name, with an
1827
+ // optional context to run the handler within
1828
+ setHandler: function(name, handler, context){
1829
+ var config = {
1830
+ callback: handler,
1831
+ context: context
1832
+ };
1833
+
1834
+ this._wreqrHandlers[name] = config;
1835
+
1836
+ this.trigger("handler:add", name, handler, context);
1837
+ },
1838
+
1839
+ // Determine whether or not a handler is registered
1840
+ hasHandler: function(name){
1841
+ return !! this._wreqrHandlers[name];
1842
+ },
1843
+
1844
+ // Get the currently registered handler for
1845
+ // the specified name. Throws an exception if
1846
+ // no handler is found.
1847
+ getHandler: function(name){
1848
+ var config = this._wreqrHandlers[name];
1849
+
1850
+ if (!config){
1851
+ throw new Error("Handler not found for '" + name + "'");
1852
+ }
1853
+
1854
+ return function(){
1855
+ var args = Array.prototype.slice.apply(arguments);
1856
+ return config.callback.apply(config.context, args);
1857
+ };
1858
+ },
1859
+
1860
+ // Remove a handler for the specified name
1861
+ removeHandler: function(name){
1862
+ delete this._wreqrHandlers[name];
1863
+ },
1864
+
1865
+ // Remove all handlers from this registry
1866
+ removeAllHandlers: function(){
1867
+ this._wreqrHandlers = {};
1868
+ }
1869
+ });
1870
+
1871
+ return Handlers;
1872
+ })(Backbone, _);
1873
+
1874
+ // Wreqr.CommandStorage
1875
+ // --------------------
1876
+ //
1877
+ // Store and retrieve commands for execution.
1878
+ Wreqr.CommandStorage = (function(){
1879
+ "use strict";
1880
+
1881
+ // Constructor function
1882
+ var CommandStorage = function(options){
1883
+ this.options = options;
1884
+ this._commands = {};
1885
+
1886
+ if (_.isFunction(this.initialize)){
1887
+ this.initialize(options);
1888
+ }
1889
+ };
1890
+
1891
+ // Instance methods
1892
+ _.extend(CommandStorage.prototype, Backbone.Events, {
1893
+
1894
+ // Get an object literal by command name, that contains
1895
+ // the `commandName` and the `instances` of all commands
1896
+ // represented as an array of arguments to process
1897
+ getCommands: function(commandName){
1898
+ var commands = this._commands[commandName];
1899
+
1900
+ // we don't have it, so add it
1901
+ if (!commands){
1902
+
1903
+ // build the configuration
1904
+ commands = {
1905
+ command: commandName,
1906
+ instances: []
1746
1907
  };
1747
- },
1748
-
1749
- // Remove a handler for the specified name
1750
- removeHandler: function(name){
1751
- delete this._handlers[name];
1752
- },
1753
-
1754
- // Remove all handlers from this registry
1755
- removeAllHandlers: function(){
1756
- this._handlers = {};
1908
+
1909
+ // store it
1910
+ this._commands[commandName] = commands;
1757
1911
  }
1758
- });
1759
-
1760
- return Handlers;
1761
- })(Backbone, _);
1762
-
1912
+
1913
+ return commands;
1914
+ },
1915
+
1916
+ // Add a command by name, to the storage and store the
1917
+ // args for the command
1918
+ addCommand: function(commandName, args){
1919
+ var command = this.getCommands(commandName);
1920
+ command.instances.push(args);
1921
+ },
1922
+
1923
+ // Clear all commands for the given `commandName`
1924
+ clearCommands: function(commandName){
1925
+ var command = this.getCommands(commandName);
1926
+ command.instances = [];
1927
+ }
1928
+ });
1929
+
1930
+ return CommandStorage;
1931
+ })();
1932
+
1763
1933
  // Wreqr.Commands
1764
- // --------------
1765
- //
1766
- // A simple command pattern implementation. Register a command
1767
- // handler and execute it.
1768
- Wreqr.Commands = (function(Wreqr){
1769
- "use strict";
1770
-
1771
- return Wreqr.Handlers.extend({
1772
- execute: function(){
1773
- var name = arguments[0];
1774
- var args = Array.prototype.slice.call(arguments, 1);
1775
-
1934
+ // --------------
1935
+ //
1936
+ // A simple command pattern implementation. Register a command
1937
+ // handler and execute it.
1938
+ Wreqr.Commands = (function(Wreqr){
1939
+ "use strict";
1940
+
1941
+ return Wreqr.Handlers.extend({
1942
+ // default storage type
1943
+ storageType: Wreqr.CommandStorage,
1944
+
1945
+ constructor: function(options){
1946
+ this.options = options || {};
1947
+
1948
+ this._initializeStorage(this.options);
1949
+ this.on("handler:add", this._executeCommands, this);
1950
+
1951
+ var args = Array.prototype.slice.call(arguments);
1952
+ Wreqr.Handlers.prototype.constructor.apply(this, args);
1953
+ },
1954
+
1955
+ // Execute a named command with the supplied args
1956
+ execute: function(name, args){
1957
+ name = arguments[0];
1958
+ args = Array.prototype.slice.call(arguments, 1);
1959
+
1960
+ if (this.hasHandler(name)){
1776
1961
  this.getHandler(name).apply(this, args);
1962
+ } else {
1963
+ this.storage.addCommand(name, args);
1777
1964
  }
1778
- });
1779
-
1780
- })(Wreqr);
1781
-
1782
- // Wreqr.RequestResponse
1783
- // ---------------------
1784
- //
1785
- // A simple request/response implementation. Register a
1786
- // request handler, and return a response from it
1787
- Wreqr.RequestResponse = (function(Wreqr){
1788
- "use strict";
1789
-
1790
- return Wreqr.Handlers.extend({
1791
- request: function(){
1792
- var name = arguments[0];
1793
- var args = Array.prototype.slice.call(arguments, 1);
1794
-
1795
- return this.getHandler(name).apply(this, args);
1965
+
1966
+ },
1967
+
1968
+ // Internal method to handle bulk execution of stored commands
1969
+ _executeCommands: function(name, handler, context){
1970
+ var command = this.storage.getCommands(name);
1971
+
1972
+ // loop through and execute all the stored command instances
1973
+ _.each(command.instances, function(args){
1974
+ handler.apply(context, args);
1975
+ });
1976
+
1977
+ this.storage.clearCommands(name);
1978
+ },
1979
+
1980
+ // Internal method to initialize storage either from the type's
1981
+ // `storageType` or the instance `options.storageType`.
1982
+ _initializeStorage: function(options){
1983
+ var storage;
1984
+
1985
+ var StorageType = options.storageType || this.storageType;
1986
+ if (_.isFunction(StorageType)){
1987
+ storage = new StorageType();
1988
+ } else {
1989
+ storage = StorageType;
1796
1990
  }
1797
- });
1798
-
1799
- })(Wreqr);
1800
-
1991
+
1992
+ this.storage = storage;
1993
+ }
1994
+ });
1995
+
1996
+ })(Wreqr);
1997
+
1998
+ // Wreqr.RequestResponse
1999
+ // ---------------------
2000
+ //
2001
+ // A simple request/response implementation. Register a
2002
+ // request handler, and return a response from it
2003
+ Wreqr.RequestResponse = (function(Wreqr){
2004
+ "use strict";
2005
+
2006
+ return Wreqr.Handlers.extend({
2007
+ request: function(){
2008
+ var name = arguments[0];
2009
+ var args = Array.prototype.slice.call(arguments, 1);
2010
+
2011
+ return this.getHandler(name).apply(this, args);
2012
+ }
2013
+ });
2014
+
2015
+ })(Wreqr);
2016
+
1801
2017
  // Event Aggregator
1802
- // ----------------
1803
- // A pub-sub object that can be used to decouple various parts
1804
- // of an application through event-driven architecture.
1805
-
1806
- Wreqr.EventAggregator = (function(Backbone, _){
1807
- "use strict";
1808
- var EA = function(){};
1809
-
1810
- // Copy the `extend` function used by Backbone's classes
1811
- EA.extend = Backbone.Model.extend;
1812
-
1813
- // Copy the basic Backbone.Events on to the event aggregator
1814
- _.extend(EA.prototype, Backbone.Events);
1815
-
1816
- return EA;
1817
- })(Backbone, _);
1818
-
2018
+ // ----------------
2019
+ // A pub-sub object that can be used to decouple various parts
2020
+ // of an application through event-driven architecture.
2021
+
2022
+ Wreqr.EventAggregator = (function(Backbone, _){
2023
+ "use strict";
2024
+ var EA = function(){};
2025
+
2026
+ // Copy the `extend` function used by Backbone's classes
2027
+ EA.extend = Backbone.Model.extend;
2028
+
2029
+ // Copy the basic Backbone.Events on to the event aggregator
2030
+ _.extend(EA.prototype, Backbone.Events);
2031
+
2032
+ return EA;
2033
+ })(Backbone, _);
2034
+
1819
2035
 
1820
2036
  return Wreqr;
1821
2037
  })(Backbone, Backbone.Marionette, _);
1822
- // Backbone.Marionette, v1.0.0-rc4
1823
- // Copyright (c)2013 Derick Bailey, Muted Solutions, LLC.
1824
- // Distributed under MIT license
1825
- // http://github.com/marionettejs/backbone.marionette
1826
2038
 
1827
- var Marionette = (function(Backbone, _, $){
2039
+ var Marionette = (function(global, Backbone, _){
1828
2040
  "use strict";
1829
2041
 
2042
+ // Define and export the Marionette namespace
1830
2043
  var Marionette = {};
1831
2044
  Backbone.Marionette = Marionette;
1832
2045
 
2046
+ // Get the DOM manipulator for later use
2047
+ Marionette.$ = Backbone.$;
2048
+
1833
2049
  // Helpers
1834
2050
  // -------
1835
2051
 
1836
2052
  // For slicing `arguments` in functions
1837
- var slice = Array.prototype.slice;
2053
+ var protoSlice = Array.prototype.slice;
2054
+ function slice(args) {
2055
+ return protoSlice.call(args);
2056
+ }
2057
+
2058
+ function throwError(message, name) {
2059
+ var error = new Error(message);
2060
+ error.name = name || 'Error';
2061
+ throw error;
2062
+ }
1838
2063
 
1839
2064
  // Marionette.extend
1840
2065
  // -----------------
@@ -1860,55 +2085,6 @@ Marionette.getOption = function(target, optionName){
1860
2085
  return value;
1861
2086
  };
1862
2087
 
1863
- // Mairionette.createObject
1864
- // ------------------------
1865
-
1866
- // A wrapper / shim for `Object.create`. Uses native `Object.create`
1867
- // if available, otherwise shims it in place for Marionette to use.
1868
- Marionette.createObject = (function(){
1869
- var createObject;
1870
-
1871
- // Define this once, and just replace the .prototype on it as needed,
1872
- // to improve performance in older / less optimized JS engines
1873
- function F() {}
1874
-
1875
-
1876
- // Check for existing native / shimmed Object.create
1877
- if (typeof Object.create === "function"){
1878
-
1879
- // found native/shim, so use it
1880
- createObject = Object.create;
1881
-
1882
- } else {
1883
-
1884
- // An implementation of the Boodman/Crockford delegation
1885
- // w/ Cornford optimization, as suggested by @unscriptable
1886
- // https://gist.github.com/3959151
1887
-
1888
- // native/shim not found, so shim it ourself
1889
- createObject = function (o) {
1890
-
1891
- // set the prototype of the function
1892
- // so we will get `o` as the prototype
1893
- // of the new object instance
1894
- F.prototype = o;
1895
-
1896
- // create a new object that inherits from
1897
- // the `o` parameter
1898
- var child = new F();
1899
-
1900
- // clean up just in case o is really large
1901
- F.prototype = null;
1902
-
1903
- // send it back
1904
- return child;
1905
- };
1906
-
1907
- }
1908
-
1909
- return createObject;
1910
- })();
1911
-
1912
2088
  // Trigger an event and a corresponding method name. Examples:
1913
2089
  //
1914
2090
  // `this.triggerMethod("foo")` will trigger the "foo" event and
@@ -1916,25 +2092,35 @@ Marionette.createObject = (function(){
1916
2092
  //
1917
2093
  // `this.triggerMethod("foo:bar") will trigger the "foo:bar" event and
1918
2094
  // call the "onFooBar" method.
1919
- Marionette.triggerMethod = function(){
1920
- var args = Array.prototype.slice.apply(arguments);
1921
- var eventName = args[0];
1922
- var segments = eventName.split(":");
1923
- var segment, capLetter, methodName = "on";
1924
-
1925
- for (var i = 0; i < segments.length; i++){
1926
- segment = segments[i];
1927
- capLetter = segment.charAt(0).toUpperCase();
1928
- methodName += capLetter + segment.slice(1);
2095
+ Marionette.triggerMethod = (function(){
2096
+
2097
+ // split the event name on the :
2098
+ var splitter = /(^|:)(\w)/gi;
2099
+
2100
+ // take the event section ("section1:section2:section3")
2101
+ // and turn it in to uppercase name
2102
+ function getEventName(match, prefix, eventName) {
2103
+ return eventName.toUpperCase();
1929
2104
  }
1930
2105
 
1931
- this.trigger.apply(this, args);
2106
+ // actual triggerMethod name
2107
+ var triggerMethod = function(event) {
2108
+ // get the method name from the event name
2109
+ var methodName = 'on' + event.replace(splitter, getEventName);
2110
+ var method = this[methodName];
1932
2111
 
1933
- if (_.isFunction(this[methodName])){
1934
- args.shift();
1935
- return this[methodName].apply(this, args);
1936
- }
1937
- };
2112
+ // trigger the event
2113
+ this.trigger.apply(this, arguments);
2114
+
2115
+ // call the onMethodName if it exists
2116
+ if (_.isFunction(method)) {
2117
+ // pass all arguments, except the event name
2118
+ return method.apply(this, _.tail(arguments));
2119
+ }
2120
+ };
2121
+
2122
+ return triggerMethod;
2123
+ })();
1938
2124
 
1939
2125
  // DOMRefresh
1940
2126
  // ----------
@@ -1985,7 +2171,7 @@ Marionette.MonitorDOMRefresh = (function(){
1985
2171
  // These methods are used to bind/unbind a backbone "entity" (collection/model)
1986
2172
  // to methods on a target object.
1987
2173
  //
1988
- // The first paremter, `target`, must have a `listenTo` method from the
2174
+ // The first parameter, `target`, must have a `listenTo` method from the
1989
2175
  // EventBinder object.
1990
2176
  //
1991
2177
  // The second parameter is the entity (Backbone.Model or Backbone.Collection)
@@ -2007,7 +2193,7 @@ Marionette.MonitorDOMRefresh = (function(){
2007
2193
 
2008
2194
  var method = target[methodName];
2009
2195
  if(!method) {
2010
- throw new Error("Method '"+ methodName +"' was configured as an event handler, but does not exist.");
2196
+ throwError("Method '"+ methodName +"' was configured as an event handler, but does not exist.");
2011
2197
  }
2012
2198
 
2013
2199
  target.listenTo(entity, evt, method, target);
@@ -2070,7 +2256,7 @@ Marionette.MonitorDOMRefresh = (function(){
2070
2256
 
2071
2257
  })(Marionette);
2072
2258
 
2073
-
2259
+
2074
2260
  // Callbacks
2075
2261
  // ---------
2076
2262
 
@@ -2078,7 +2264,7 @@ Marionette.MonitorDOMRefresh = (function(){
2078
2264
  // and executing them at a later point in time, using jQuery's
2079
2265
  // `Deferred` object.
2080
2266
  Marionette.Callbacks = function(){
2081
- this._deferred = $.Deferred();
2267
+ this._deferred = Marionette.$.Deferred();
2082
2268
  this._callbacks = [];
2083
2269
  };
2084
2270
 
@@ -2106,13 +2292,13 @@ _.extend(Marionette.Callbacks.prototype, {
2106
2292
  // Resets the list of callbacks to be run, allowing the same list
2107
2293
  // to be run multiple times - whenever the `run` method is called.
2108
2294
  reset: function(){
2109
- var that = this;
2110
2295
  var callbacks = this._callbacks;
2111
- this._deferred = $.Deferred();
2296
+ this._deferred = Marionette.$.Deferred();
2112
2297
  this._callbacks = [];
2298
+
2113
2299
  _.each(callbacks, function(cb){
2114
- that.add(cb.cb, cb.ctx);
2115
- });
2300
+ this.add(cb.cb, cb.ctx);
2301
+ }, this);
2116
2302
  }
2117
2303
  });
2118
2304
 
@@ -2226,12 +2412,28 @@ _.extend(Marionette.Region, {
2226
2412
  }
2227
2413
 
2228
2414
  // build the region instance
2229
-
2230
- var regionManager = new RegionType({
2415
+ var region = new RegionType({
2231
2416
  el: selector
2232
2417
  });
2233
2418
 
2234
- return regionManager;
2419
+ // override the `getEl` function if we have a parentEl
2420
+ // this must be overridden to ensure the selector is found
2421
+ // on the first use of the region. if we try to assign the
2422
+ // region's `el` to `parentEl.find(selector)` in the object
2423
+ // literal to build the region, the element will not be
2424
+ // guaranteed to be in the DOM already, and will cause problems
2425
+ if (regionConfig.parentEl){
2426
+
2427
+ region.getEl = function(selector) {
2428
+ var parentEl = regionConfig.parentEl;
2429
+ if (_.isFunction(parentEl)){
2430
+ parentEl = parentEl();
2431
+ }
2432
+ return parentEl.find(selector);
2433
+ };
2434
+ }
2435
+
2436
+ return region;
2235
2437
  }
2236
2438
 
2237
2439
  });
@@ -2249,10 +2451,14 @@ _.extend(Marionette.Region.prototype, Backbone.Events, {
2249
2451
  show: function(view){
2250
2452
 
2251
2453
  this.ensureEl();
2252
- this.close();
2253
2454
 
2254
- view.render();
2255
- this.open(view);
2455
+ if (view !== this.currentView) {
2456
+ this.close();
2457
+ view.render();
2458
+ this.open(view);
2459
+ } else {
2460
+ view.render();
2461
+ }
2256
2462
 
2257
2463
  Marionette.triggerMethod.call(view, "show");
2258
2464
  Marionette.triggerMethod.call(this, "show", view);
@@ -2269,7 +2475,7 @@ _.extend(Marionette.Region.prototype, Backbone.Events, {
2269
2475
  // Override this method to change how the region finds the
2270
2476
  // DOM element that it manages. Return a jQuery selector object.
2271
2477
  getEl: function(selector){
2272
- return $(selector);
2478
+ return Marionette.$(selector);
2273
2479
  },
2274
2480
 
2275
2481
  // Override this method to change how the new view is
@@ -2284,7 +2490,10 @@ _.extend(Marionette.Region.prototype, Backbone.Events, {
2284
2490
  var view = this.currentView;
2285
2491
  if (!view || view.isClosed){ return; }
2286
2492
 
2493
+ // call 'close' or 'remove', depending on which is found
2287
2494
  if (view.close) { view.close(); }
2495
+ else if (view.remove) { view.remove(); }
2496
+
2288
2497
  Marionette.triggerMethod.call(this, "close");
2289
2498
 
2290
2499
  delete this.currentView;
@@ -2311,6 +2520,133 @@ _.extend(Marionette.Region.prototype, Backbone.Events, {
2311
2520
  // Copy the `extend` function used by Backbone's classes
2312
2521
  Marionette.Region.extend = Marionette.extend;
2313
2522
 
2523
+ // Marionette.RegionManager
2524
+ // ------------------------
2525
+ //
2526
+ // Manage one or more related `Marionette.Region` objects.
2527
+ Marionette.RegionManager = (function(Marionette){
2528
+
2529
+ var RegionManager = Marionette.Controller.extend({
2530
+ constructor: function(options){
2531
+ this._regions = {};
2532
+ Marionette.Controller.prototype.constructor.call(this, options);
2533
+ },
2534
+
2535
+ // Add multiple regions using an object literal, where
2536
+ // each key becomes the region name, and each value is
2537
+ // the region definition.
2538
+ addRegions: function(regionDefinitions, defaults){
2539
+ var regions = {};
2540
+
2541
+ _.each(regionDefinitions, function(definition, name){
2542
+ if (typeof definition === "string"){
2543
+ definition = { selector: definition };
2544
+ }
2545
+
2546
+ if (definition.selector){
2547
+ definition = _.defaults({}, definition, defaults);
2548
+ }
2549
+
2550
+ var region = this.addRegion(name, definition);
2551
+ regions[name] = region;
2552
+ }, this);
2553
+
2554
+ return regions;
2555
+ },
2556
+
2557
+ // Add an individual region to the region manager,
2558
+ // and return the region instance
2559
+ addRegion: function(name, definition){
2560
+ var region;
2561
+
2562
+ var isObject = _.isObject(definition);
2563
+ var isString = _.isString(definition);
2564
+ var hasSelector = !!definition.selector;
2565
+
2566
+ if (isString || (isObject && hasSelector)){
2567
+ region = Marionette.Region.buildRegion(definition, Marionette.Region);
2568
+ } else if (_.isFunction(definition)){
2569
+ region = Marionette.Region.buildRegion(definition, Marionette.Region);
2570
+ } else {
2571
+ region = definition;
2572
+ }
2573
+
2574
+ this._store(name, region);
2575
+ this.triggerMethod("region:add", name, region);
2576
+ return region;
2577
+ },
2578
+
2579
+ // Get a region by name
2580
+ get: function(name){
2581
+ return this._regions[name];
2582
+ },
2583
+
2584
+ // Remove a region by name
2585
+ removeRegion: function(name){
2586
+ var region = this._regions[name];
2587
+ this._remove(name, region);
2588
+ },
2589
+
2590
+ // Close all regions in the region manager, and
2591
+ // remove them
2592
+ removeRegions: function(){
2593
+ _.each(this._regions, function(region, name){
2594
+ this._remove(name, region);
2595
+ }, this);
2596
+ },
2597
+
2598
+ // Close all regions in the region manager, but
2599
+ // leave them attached
2600
+ closeRegions: function(){
2601
+ _.each(this._regions, function(region, name){
2602
+ region.close();
2603
+ }, this);
2604
+ },
2605
+
2606
+ // Close all regions and shut down the region
2607
+ // manager entirely
2608
+ close: function(){
2609
+ this.removeRegions();
2610
+ var args = Array.prototype.slice.call(arguments);
2611
+ Marionette.Controller.prototype.close.apply(this, args);
2612
+ },
2613
+
2614
+ // internal method to store regions
2615
+ _store: function(name, region){
2616
+ this._regions[name] = region;
2617
+ this.length = _.size(this._regions);
2618
+ },
2619
+
2620
+ // internal method to remove a region
2621
+ _remove: function(name, region){
2622
+ region.close();
2623
+ delete this._regions[name];
2624
+ this.triggerMethod("region:remove", name, region);
2625
+ }
2626
+
2627
+ });
2628
+
2629
+ // Borrowing this code from Backbone.Collection:
2630
+ // http://backbonejs.org/docs/backbone.html#section-106
2631
+ //
2632
+ // Mix in methods from Underscore, for iteration, and other
2633
+ // collection related features.
2634
+ var methods = ['forEach', 'each', 'map', 'find', 'detect', 'filter',
2635
+ 'select', 'reject', 'every', 'all', 'some', 'any', 'include',
2636
+ 'contains', 'invoke', 'toArray', 'first', 'initial', 'rest',
2637
+ 'last', 'without', 'isEmpty', 'pluck'];
2638
+
2639
+ _.each(methods, function(method) {
2640
+ RegionManager.prototype[method] = function() {
2641
+ var regions = _.values(this._regions);
2642
+ var args = [regions].concat(_.toArray(arguments));
2643
+ return _[method].apply(_, args);
2644
+ };
2645
+ });
2646
+
2647
+ return RegionManager;
2648
+ })(Marionette);
2649
+
2314
2650
 
2315
2651
  // Template Cache
2316
2652
  // --------------
@@ -2331,7 +2667,6 @@ _.extend(Marionette.TemplateCache, {
2331
2667
  // retrieves the cached version, or loads it
2332
2668
  // from the DOM.
2333
2669
  get: function(templateId){
2334
- var that = this;
2335
2670
  var cachedTemplate = this.templateCaches[templateId];
2336
2671
 
2337
2672
  if (!cachedTemplate){
@@ -2351,7 +2686,7 @@ _.extend(Marionette.TemplateCache, {
2351
2686
  // `clear("#t1", "#t2", "...")`
2352
2687
  clear: function(){
2353
2688
  var i;
2354
- var args = Array.prototype.slice.apply(arguments);
2689
+ var args = slice(arguments);
2355
2690
  var length = args.length;
2356
2691
 
2357
2692
  if (length > 0){
@@ -2371,8 +2706,6 @@ _.extend(Marionette.TemplateCache.prototype, {
2371
2706
 
2372
2707
  // Internal method to load the template
2373
2708
  load: function(){
2374
- var that = this;
2375
-
2376
2709
  // Guard clause to prevent loading this template more than once
2377
2710
  if (this.compiledTemplate){
2378
2711
  return this.compiledTemplate;
@@ -2391,13 +2724,10 @@ _.extend(Marionette.TemplateCache.prototype, {
2391
2724
  // using a template-loader plugin as described here:
2392
2725
  // https://github.com/marionettejs/backbone.marionette/wiki/Using-marionette-with-requirejs
2393
2726
  loadTemplate: function(templateId){
2394
- var template = $(templateId).html();
2727
+ var template = Marionette.$(templateId).html();
2395
2728
 
2396
2729
  if (!template || template.length === 0){
2397
- var msg = "Could not find template: '" + templateId + "'";
2398
- var err = new Error(msg);
2399
- err.name = "NoTemplateError";
2400
- throw err;
2730
+ throwError("Could not find template: '" + templateId + "'", "NoTemplateError");
2401
2731
  }
2402
2732
 
2403
2733
  return template;
@@ -2426,8 +2756,7 @@ Marionette.Renderer = {
2426
2756
  // custom rendering and template handling for all of Marionette.
2427
2757
  render: function(template, data){
2428
2758
  var templateFunc = typeof template === 'function' ? template : Marionette.TemplateCache.get(template);
2429
- var html = templateFunc(data);
2430
- return html;
2759
+ return templateFunc(data);
2431
2760
  }
2432
2761
  };
2433
2762
 
@@ -2480,7 +2809,6 @@ Marionette.View = Backbone.View.extend({
2480
2809
  configureTriggers: function(){
2481
2810
  if (!this.triggers) { return; }
2482
2811
 
2483
- var that = this;
2484
2812
  var triggerEvents = {};
2485
2813
 
2486
2814
  // Allow `triggers` to be configured as a function
@@ -2497,7 +2825,7 @@ Marionette.View = Backbone.View.extend({
2497
2825
  if (e && e.preventDefault){ e.preventDefault(); }
2498
2826
  if (e && e.stopPropagation){ e.stopPropagation(); }
2499
2827
 
2500
- // buil the args for the event
2828
+ // build the args for the event
2501
2829
  var args = {
2502
2830
  view: this,
2503
2831
  model: this.model,
@@ -2505,10 +2833,10 @@ Marionette.View = Backbone.View.extend({
2505
2833
  };
2506
2834
 
2507
2835
  // trigger the event
2508
- that.triggerMethod(value, args);
2836
+ this.triggerMethod(value, args);
2509
2837
  };
2510
2838
 
2511
- });
2839
+ }, this);
2512
2840
 
2513
2841
  return triggerEvents;
2514
2842
  },
@@ -2566,6 +2894,10 @@ Marionette.View = Backbone.View.extend({
2566
2894
  this.isClosed = true;
2567
2895
  this.triggerMethod("close");
2568
2896
 
2897
+ // unbind UI elements
2898
+ this.unbindUIElements();
2899
+
2900
+ // remove the view from the DOM
2569
2901
  this.remove();
2570
2902
  },
2571
2903
 
@@ -2574,20 +2906,37 @@ Marionette.View = Backbone.View.extend({
2574
2906
  bindUIElements: function(){
2575
2907
  if (!this.ui) { return; }
2576
2908
 
2577
- var that = this;
2578
-
2579
- if (!this.uiBindings) {
2580
- // We want to store the ui hash in uiBindings, since afterwards the values in the ui hash
2581
- // will be overridden with jQuery selectors.
2582
- this.uiBindings = _.result(this, "ui");
2909
+ // store the ui hash in _uiBindings so they can be reset later
2910
+ // and so re-rendering the view will be able to find the bindings
2911
+ if (!this._uiBindings){
2912
+ this._uiBindings = this.ui;
2583
2913
  }
2584
2914
 
2585
- // refreshing the associated selectors since they should point to the newly rendered elements.
2915
+ // get the bindings result, as a function or otherwise
2916
+ var bindings = _.result(this, "_uiBindings");
2917
+
2918
+ // empty the ui so we don't have anything to start with
2586
2919
  this.ui = {};
2587
- _.each(_.keys(this.uiBindings), function(key) {
2588
- var selector = that.uiBindings[key];
2589
- that.ui[key] = that.$(selector);
2590
- });
2920
+
2921
+ // bind each of the selectors
2922
+ _.each(_.keys(bindings), function(key) {
2923
+ var selector = bindings[key];
2924
+ this.ui[key] = this.$(selector);
2925
+ }, this);
2926
+ },
2927
+
2928
+ // This method unbinds the elements specified in the "ui" hash
2929
+ unbindUIElements: function(){
2930
+ if (!this.ui){ return; }
2931
+
2932
+ // delete all of the existing ui bindings
2933
+ _.each(this.ui, function($el, name){
2934
+ delete this.ui[name];
2935
+ }, this);
2936
+
2937
+ // reset the ui element to the original bindings configuration
2938
+ this.ui = this._uiBindings;
2939
+ delete this._uiBindings;
2591
2940
  }
2592
2941
  });
2593
2942
 
@@ -2599,8 +2948,7 @@ Marionette.View = Backbone.View.extend({
2599
2948
  // and calling several methods on extended views, such as `onRender`.
2600
2949
  Marionette.ItemView = Marionette.View.extend({
2601
2950
  constructor: function(){
2602
- var args = Array.prototype.slice.apply(arguments);
2603
- Marionette.View.prototype.constructor.apply(this, args);
2951
+ Marionette.View.prototype.constructor.apply(this, slice(arguments));
2604
2952
  },
2605
2953
 
2606
2954
  // Serialize the model or collection for the view. If a model is
@@ -2654,8 +3002,7 @@ Marionette.ItemView = Marionette.View.extend({
2654
3002
 
2655
3003
  this.triggerMethod('item:before:close');
2656
3004
 
2657
- var args = Array.prototype.slice.apply(arguments);
2658
- Marionette.View.prototype.close.apply(this, args);
3005
+ Marionette.View.prototype.close.apply(this, slice(arguments));
2659
3006
 
2660
3007
  this.triggerMethod('item:closed');
2661
3008
  }
@@ -2675,8 +3022,7 @@ Marionette.CollectionView = Marionette.View.extend({
2675
3022
  constructor: function(options){
2676
3023
  this._initChildViewStorage();
2677
3024
 
2678
- var args = Array.prototype.slice.apply(arguments);
2679
- Marionette.View.prototype.constructor.apply(this, args);
3025
+ Marionette.View.prototype.constructor.apply(this, slice(arguments));
2680
3026
 
2681
3027
  this._initialEvents();
2682
3028
  },
@@ -2727,8 +3073,16 @@ Marionette.CollectionView = Marionette.View.extend({
2727
3073
  // the collection view.
2728
3074
  render: function(){
2729
3075
  this.isClosed = false;
2730
-
2731
3076
  this.triggerBeforeRender();
3077
+ this._renderChildren();
3078
+ this.triggerRendered();
3079
+ return this;
3080
+ },
3081
+
3082
+ // Internal method. Separated so that CompositeView can have
3083
+ // more control over events being triggered, around the rendering
3084
+ // process
3085
+ _renderChildren: function(){
2732
3086
  this.closeEmptyView();
2733
3087
  this.closeChildren();
2734
3088
 
@@ -2737,20 +3091,16 @@ Marionette.CollectionView = Marionette.View.extend({
2737
3091
  } else {
2738
3092
  this.showEmptyView();
2739
3093
  }
2740
-
2741
- this.triggerRendered();
2742
- return this;
2743
3094
  },
2744
3095
 
2745
3096
  // Internal method to loop through each item in the
2746
3097
  // collection view and show it
2747
3098
  showCollection: function(){
2748
- var that = this;
2749
3099
  var ItemView;
2750
3100
  this.collection.each(function(item, index){
2751
- ItemView = that.getItemView(item);
2752
- that.addItemView(item, ItemView, index);
2753
- });
3101
+ ItemView = this.getItemView(item);
3102
+ this.addItemView(item, ItemView, index);
3103
+ }, this);
2754
3104
  },
2755
3105
 
2756
3106
  // Internal method to show an empty view in place of
@@ -2783,9 +3133,7 @@ Marionette.CollectionView = Marionette.View.extend({
2783
3133
  var itemView = Marionette.getOption(this, "itemView");
2784
3134
 
2785
3135
  if (!itemView){
2786
- var err = new Error("An `itemView` must be specified");
2787
- err.name = "NoItemViewError";
2788
- throw err;
3136
+ throwError("An `itemView` must be specified", "NoItemViewError");
2789
3137
  }
2790
3138
 
2791
3139
  return itemView;
@@ -2794,12 +3142,10 @@ Marionette.CollectionView = Marionette.View.extend({
2794
3142
  // Render the child item's view and add it to the
2795
3143
  // HTML for the collection view.
2796
3144
  addItemView: function(item, ItemView, index){
2797
- var that = this;
2798
-
2799
3145
  // get the itemViewOptions if any were specified
2800
3146
  var itemViewOptions = Marionette.getOption(this, "itemViewOptions");
2801
3147
  if (_.isFunction(itemViewOptions)){
2802
- itemViewOptions = itemViewOptions.call(this, item);
3148
+ itemViewOptions = itemViewOptions.call(this, item, index);
2803
3149
  }
2804
3150
 
2805
3151
  // build the view
@@ -2815,15 +3161,15 @@ Marionette.CollectionView = Marionette.View.extend({
2815
3161
  // remove and/or close it later
2816
3162
  this.children.add(view);
2817
3163
 
3164
+ // Render it and show it
3165
+ this.renderItemView(view, index);
3166
+
2818
3167
  // call the "show" method if the collection view
2819
3168
  // has already been shown
2820
3169
  if (this._isShown){
2821
3170
  Marionette.triggerMethod.call(view, "show");
2822
3171
  }
2823
3172
 
2824
- // Render it and show it
2825
- var renderResult = this.renderItemView(view, index);
2826
-
2827
3173
  // this view was added
2828
3174
  this.triggerMethod("after:item:added", view);
2829
3175
  },
@@ -2836,7 +3182,7 @@ Marionette.CollectionView = Marionette.View.extend({
2836
3182
  // Forward all child item view events through the parent,
2837
3183
  // prepending "itemview:" to the event name
2838
3184
  this.listenTo(view, "all", function(){
2839
- var args = slice.call(arguments);
3185
+ var args = slice(arguments);
2840
3186
  args[0] = prefix + ":" + args[0];
2841
3187
  args.splice(1, 0, view);
2842
3188
 
@@ -2853,8 +3199,7 @@ Marionette.CollectionView = Marionette.View.extend({
2853
3199
  // Build an `itemView` for every model in the collection.
2854
3200
  buildItemView: function(item, ItemViewType, itemViewOptions){
2855
3201
  var options = _.extend({model: item}, itemViewOptions);
2856
- var view = new ItemViewType(options);
2857
- return view;
3202
+ return new ItemViewType(options);
2858
3203
  },
2859
3204
 
2860
3205
  // get the child view by item it holds, and remove it
@@ -2872,9 +3217,9 @@ Marionette.CollectionView = Marionette.View.extend({
2872
3217
  if (view){
2873
3218
  this.stopListening(view);
2874
3219
 
2875
- if (view.close){
2876
- view.close();
2877
- }
3220
+ // call 'close' or 'remove', depending on which is found
3221
+ if (view.close) { view.close(); }
3222
+ else if (view.remove) { view.remove(); }
2878
3223
 
2879
3224
  this.children.remove(view);
2880
3225
  }
@@ -2913,8 +3258,7 @@ Marionette.CollectionView = Marionette.View.extend({
2913
3258
  this.closeChildren();
2914
3259
  this.triggerMethod("collection:closed");
2915
3260
 
2916
- var args = Array.prototype.slice.apply(arguments);
2917
- Marionette.View.prototype.close.apply(this, args);
3261
+ Marionette.View.prototype.close.apply(this, slice(arguments));
2918
3262
  },
2919
3263
 
2920
3264
  // Close the child views that this collection view
@@ -2936,8 +3280,7 @@ Marionette.CollectionView = Marionette.View.extend({
2936
3280
  // an item view as `modelView`, for the top leaf
2937
3281
  Marionette.CompositeView = Marionette.CollectionView.extend({
2938
3282
  constructor: function(options){
2939
- var args = Array.prototype.slice.apply(arguments);
2940
- Marionette.CollectionView.apply(this, args);
3283
+ Marionette.CollectionView.apply(this, slice(arguments));
2941
3284
 
2942
3285
  this.itemView = this.getItemView();
2943
3286
  },
@@ -2949,7 +3292,7 @@ Marionette.CompositeView = Marionette.CollectionView.extend({
2949
3292
  if (this.collection){
2950
3293
  this.listenTo(this.collection, "add", this.addChildView, this);
2951
3294
  this.listenTo(this.collection, "remove", this.removeItemView, this);
2952
- this.listenTo(this.collection, "reset", this.renderCollection, this);
3295
+ this.listenTo(this.collection, "reset", this._renderChildren, this);
2953
3296
  }
2954
3297
  },
2955
3298
 
@@ -2961,9 +3304,7 @@ Marionette.CompositeView = Marionette.CollectionView.extend({
2961
3304
  var itemView = Marionette.getOption(this, "itemView") || this.constructor;
2962
3305
 
2963
3306
  if (!itemView){
2964
- var err = new Error("An `itemView` must be specified");
2965
- err.name = "NoItemViewError";
2966
- throw err;
3307
+ throwError("An `itemView` must be specified", "NoItemViewError");
2967
3308
  }
2968
3309
 
2969
3310
  return itemView;
@@ -2986,31 +3327,31 @@ Marionette.CompositeView = Marionette.CollectionView.extend({
2986
3327
  // this again will tell the model's view to re-render itself
2987
3328
  // but the collection will not re-render.
2988
3329
  render: function(){
3330
+ this.isRendered = true;
2989
3331
  this.isClosed = false;
2990
-
2991
3332
  this.resetItemViewContainer();
2992
3333
 
3334
+ this.triggerBeforeRender();
2993
3335
  var html = this.renderModel();
2994
3336
  this.$el.html(html);
2995
-
2996
3337
  // the ui bindings is done here and not at the end of render since they
2997
3338
  // will not be available until after the model is rendered, but should be
2998
3339
  // available before the collection is rendered.
2999
3340
  this.bindUIElements();
3000
-
3001
3341
  this.triggerMethod("composite:model:rendered");
3002
3342
 
3003
- this.renderCollection();
3343
+ this._renderChildren();
3344
+
3004
3345
  this.triggerMethod("composite:rendered");
3346
+ this.triggerRendered();
3005
3347
  return this;
3006
3348
  },
3007
3349
 
3008
- // Render the collection for the composite view
3009
- renderCollection: function(){
3010
- var args = Array.prototype.slice.apply(arguments);
3011
- Marionette.CollectionView.prototype.render.apply(this, args);
3012
-
3013
- this.triggerMethod("composite:collection:rendered");
3350
+ _renderChildren: function(){
3351
+ if (this.isRendered){
3352
+ Marionette.CollectionView.prototype._renderChildren.call(this);
3353
+ this.triggerMethod("composite:collection:rendered");
3354
+ }
3014
3355
  },
3015
3356
 
3016
3357
  // Render an individual model, if we have one, as
@@ -3047,9 +3388,7 @@ Marionette.CompositeView = Marionette.CollectionView.extend({
3047
3388
  var selector = _.result(containerView, "itemViewContainer");
3048
3389
  container = containerView.$(selector);
3049
3390
  if (container.length <= 0) {
3050
- var err = new Error("The specified `itemViewContainer` was not found: " + containerView.itemViewContainer);
3051
- err.name = "ItemViewContainerMissingError";
3052
- throw err;
3391
+ throwError("The specified `itemViewContainer` was not found: " + containerView.itemViewContainer, "ItemViewContainerMissingError");
3053
3392
  }
3054
3393
 
3055
3394
  } else {
@@ -3081,14 +3420,15 @@ Marionette.CompositeView = Marionette.CollectionView.extend({
3081
3420
  Marionette.Layout = Marionette.ItemView.extend({
3082
3421
  regionType: Marionette.Region,
3083
3422
 
3084
- // Ensure the regions are avialable when the `initialize` method
3423
+ // Ensure the regions are available when the `initialize` method
3085
3424
  // is called.
3086
- constructor: function () {
3087
- this._firstRender = true;
3088
- this.initializeRegions();
3425
+ constructor: function (options) {
3426
+ options = options || {};
3089
3427
 
3090
- var args = Array.prototype.slice.apply(arguments);
3091
- Marionette.ItemView.apply(this, args);
3428
+ this._firstRender = true;
3429
+ this._initializeRegions(options);
3430
+
3431
+ Marionette.ItemView.call(this, options);
3092
3432
  },
3093
3433
 
3094
3434
  // Layout's render will use the existing region objects the
@@ -3101,11 +3441,14 @@ Marionette.Layout = Marionette.ItemView.extend({
3101
3441
  // if this is the first render, don't do anything to
3102
3442
  // reset the regions
3103
3443
  this._firstRender = false;
3444
+ } else if (this.isClosed){
3445
+ // a previously closed layout means we need to
3446
+ // completely re-initialize the regions
3447
+ this._initializeRegions();
3104
3448
  } else {
3105
3449
  // If this is not the first render call, then we need to
3106
3450
  // re-initializing the `el` for each region
3107
- this.closeRegions();
3108
- this.reInitializeRegions();
3451
+ this._reInitializeRegions();
3109
3452
  }
3110
3453
 
3111
3454
  var args = Array.prototype.slice.apply(arguments);
@@ -3117,75 +3460,82 @@ Marionette.Layout = Marionette.ItemView.extend({
3117
3460
  // Handle closing regions, and then close the view itself.
3118
3461
  close: function () {
3119
3462
  if (this.isClosed){ return; }
3120
-
3121
- this.closeRegions();
3122
- this.destroyRegions();
3123
-
3463
+ this.regionManager.close();
3124
3464
  var args = Array.prototype.slice.apply(arguments);
3125
3465
  Marionette.ItemView.prototype.close.apply(this, args);
3126
3466
  },
3127
3467
 
3128
- // Initialize the regions that have been defined in a
3129
- // `regions` attribute on this layout. The key of the
3130
- // hash becomes an attribute on the layout object directly.
3131
- // For example: `regions: { menu: ".menu-container" }`
3132
- // will product a `layout.menu` object which is a region
3133
- // that controls the `.menu-container` DOM element.
3134
- initializeRegions: function () {
3135
- if (!this.regionManagers){
3136
- this.regionManagers = {};
3137
- }
3468
+ // Add a single region, by name, to the layout
3469
+ addRegion: function(name, definition){
3470
+ var regions = {};
3471
+ regions[name] = definition;
3472
+ return this.addRegions(regions)[name];
3473
+ },
3138
3474
 
3139
- var that = this;
3140
- var regions = this.regions || {};
3141
- _.each(regions, function (region, name) {
3475
+ // Add multiple regions as a {name: definition, name2: def2} object literal
3476
+ addRegions: function(regions){
3477
+ this.regions = _.extend(this.regions || {}, regions);
3478
+ return this._buildRegions(regions);
3479
+ },
3142
3480
 
3143
- var regionManager = Marionette.Region.buildRegion(region, that.regionType);
3144
- regionManager.getEl = function(selector){
3145
- return that.$(selector);
3146
- };
3481
+ // Remove a single region from the Layout, by name
3482
+ removeRegion: function(name){
3483
+ return this.regionManager.removeRegion(name);
3484
+ },
3147
3485
 
3148
- that.regionManagers[name] = regionManager;
3149
- that[name] = regionManager;
3150
- });
3486
+ // internal method to build regions
3487
+ _buildRegions: function(regions){
3488
+ var that = this;
3151
3489
 
3490
+ var defaults = {
3491
+ parentEl: function(){ return that.$el; }
3492
+ };
3493
+
3494
+ return this.regionManager.addRegions(regions, defaults);
3152
3495
  },
3153
3496
 
3154
- // Re-initialize all of the regions by updating the `el` that
3155
- // they point to
3156
- reInitializeRegions: function(){
3157
- if (this.regionManagers && _.size(this.regionManagers)===0){
3158
- this.initializeRegions();
3497
+ // Internal method to initialize the regions that have been defined in a
3498
+ // `regions` attribute on this layout.
3499
+ _initializeRegions: function (options) {
3500
+ var regions;
3501
+ this._initRegionManager();
3502
+
3503
+ if (_.isFunction(this.regions)) {
3504
+ regions = this.regions(options);
3159
3505
  } else {
3160
- _.each(this.regionManagers, function(region){
3161
- region.reset();
3162
- });
3506
+ regions = this.regions || {};
3163
3507
  }
3508
+
3509
+ this.addRegions(regions);
3164
3510
  },
3165
3511
 
3166
- // Close all of the regions that have been opened by
3167
- // this layout. This method is called when the layout
3168
- // itself is closed.
3169
- closeRegions: function () {
3170
- var that = this;
3171
- _.each(this.regionManagers, function (manager, name) {
3172
- manager.close();
3512
+ // Internal method to re-initialize all of the regions by updating the `el` that
3513
+ // they point to
3514
+ _reInitializeRegions: function(){
3515
+ this.regionManager.closeRegions();
3516
+ this.regionManager.each(function(region){
3517
+ region.reset();
3173
3518
  });
3174
3519
  },
3175
3520
 
3176
- // Destroys all of the regions by removing references
3177
- // from the Layout
3178
- destroyRegions: function(){
3179
- var that = this;
3180
- _.each(this.regionManagers, function (manager, name) {
3181
- delete that[name];
3521
+ // Internal method to initialize the region manager
3522
+ // and all regions in it
3523
+ _initRegionManager: function(){
3524
+ this.regionManager = new Marionette.RegionManager();
3525
+
3526
+ this.listenTo(this.regionManager, "region:add", function(name, region){
3527
+ this[name] = region;
3528
+ this.trigger("region:add", name, region);
3529
+ });
3530
+
3531
+ this.listenTo(this.regionManager, "region:remove", function(name, region){
3532
+ delete this[name];
3533
+ this.trigger("region:remove", name, region);
3182
3534
  });
3183
- this.regionManagers = {};
3184
3535
  }
3185
3536
  });
3186
3537
 
3187
3538
 
3188
-
3189
3539
  // AppRouter
3190
3540
  // ---------
3191
3541
 
@@ -3198,7 +3548,7 @@ Marionette.Layout = Marionette.ItemView.extend({
3198
3548
  //
3199
3549
  // App routers can only take one `controller` object.
3200
3550
  // It is recommended that you divide your controller
3201
- // objects in to smaller peices of related functionality
3551
+ // objects in to smaller pieces of related functionality
3202
3552
  // and have multiple routers / controllers, instead of
3203
3553
  // just one giant router and controller.
3204
3554
  //
@@ -3207,8 +3557,7 @@ Marionette.Layout = Marionette.ItemView.extend({
3207
3557
  Marionette.AppRouter = Backbone.Router.extend({
3208
3558
 
3209
3559
  constructor: function(options){
3210
- var args = Array.prototype.slice.apply(arguments);
3211
- Backbone.Router.prototype.constructor.apply(this, args);
3560
+ Backbone.Router.prototype.constructor.apply(this, slice(arguments));
3212
3561
 
3213
3562
  this.options = options;
3214
3563
 
@@ -3221,34 +3570,19 @@ Marionette.AppRouter = Backbone.Router.extend({
3221
3570
  // Internal method to process the `appRoutes` for the
3222
3571
  // router, and turn them in to routes that trigger the
3223
3572
  // specified method on the specified `controller`.
3224
- processAppRoutes: function(controller, appRoutes){
3225
- var method, methodName;
3226
- var route, routesLength, i;
3227
- var routes = [];
3228
- var router = this;
3229
-
3230
- for(route in appRoutes){
3231
- if (appRoutes.hasOwnProperty(route)){
3232
- routes.unshift([route, appRoutes[route]]);
3233
- }
3234
- }
3573
+ processAppRoutes: function(controller, appRoutes) {
3574
+ var routeNames = _.keys(appRoutes).reverse(); // Backbone requires reverted order of routes
3235
3575
 
3236
- routesLength = routes.length;
3237
- for (i = 0; i < routesLength; i++){
3238
- route = routes[i][0];
3239
- methodName = routes[i][1];
3240
- method = controller[methodName];
3241
-
3242
- if (!method){
3243
- var msg = "Method '" + methodName + "' was not found on the controller";
3244
- var err = new Error(msg);
3245
- err.name = "NoMethodError";
3246
- throw err;
3576
+ _.each(routeNames, function(route) {
3577
+ var methodName = appRoutes[route];
3578
+ var method = controller[methodName];
3579
+
3580
+ if (!method) {
3581
+ throw new Error("Method '" + methodName + "' was not found on the controller");
3247
3582
  }
3248
3583
 
3249
- method = _.bind(method, controller);
3250
- router.route(route, methodName, method);
3251
- }
3584
+ this.route(route, methodName, _.bind(method, controller));
3585
+ }, this);
3252
3586
  }
3253
3587
  });
3254
3588
 
@@ -3260,7 +3594,8 @@ Marionette.AppRouter = Backbone.Router.extend({
3260
3594
  // Stores and starts up `Region` objects, includes an
3261
3595
  // event aggregator as `app.vent`
3262
3596
  Marionette.Application = function(options){
3263
- this.initCallbacks = new Marionette.Callbacks();
3597
+ this._initRegionManager();
3598
+ this._initCallbacks = new Marionette.Callbacks();
3264
3599
  this.vent = new Backbone.Wreqr.EventAggregator();
3265
3600
  this.commands = new Backbone.Wreqr.Commands();
3266
3601
  this.reqres = new Backbone.Wreqr.RequestResponse();
@@ -3288,7 +3623,7 @@ _.extend(Marionette.Application.prototype, Backbone.Events, {
3288
3623
  // method is called, or run immediately if added after `start`
3289
3624
  // has already been called.
3290
3625
  addInitializer: function(initializer){
3291
- this.initCallbacks.add(initializer);
3626
+ this._initCallbacks.add(initializer);
3292
3627
  },
3293
3628
 
3294
3629
  // kick off all of the application's processes.
@@ -3296,7 +3631,7 @@ _.extend(Marionette.Application.prototype, Backbone.Events, {
3296
3631
  // to the app, and runs all of the initializer functions
3297
3632
  start: function(options){
3298
3633
  this.triggerMethod("initialize:before", options);
3299
- this.initCallbacks.run(options, this);
3634
+ this._initCallbacks.run(options, this);
3300
3635
  this.triggerMethod("initialize:after", options);
3301
3636
 
3302
3637
  this.triggerMethod("start", options);
@@ -3305,32 +3640,40 @@ _.extend(Marionette.Application.prototype, Backbone.Events, {
3305
3640
  // Add regions to your app.
3306
3641
  // Accepts a hash of named strings or Region objects
3307
3642
  // addRegions({something: "#someRegion"})
3308
- // addRegions{{something: Region.extend({el: "#someRegion"}) });
3643
+ // addRegions({something: Region.extend({el: "#someRegion"}) });
3309
3644
  addRegions: function(regions){
3310
- var that = this;
3311
- _.each(regions, function (region, name) {
3312
- var regionManager = Marionette.Region.buildRegion(region, Marionette.Region);
3313
- that[name] = regionManager;
3314
- });
3645
+ return this._regionManager.addRegions(regions);
3315
3646
  },
3316
3647
 
3317
3648
  // Removes a region from your app.
3318
3649
  // Accepts the regions name
3319
3650
  // removeRegion('myRegion')
3320
3651
  removeRegion: function(region) {
3321
- this[region].close();
3322
- delete this[region];
3652
+ this._regionManager.removeRegion(region);
3323
3653
  },
3324
3654
 
3325
3655
  // Create a module, attached to the application
3326
3656
  module: function(moduleNames, moduleDefinition){
3327
3657
  // slice the args, and add this application object as the
3328
3658
  // first argument of the array
3329
- var args = slice.call(arguments);
3659
+ var args = slice(arguments);
3330
3660
  args.unshift(this);
3331
3661
 
3332
3662
  // see the Marionette.Module object for more information
3333
3663
  return Marionette.Module.create.apply(Marionette.Module, args);
3664
+ },
3665
+
3666
+ // Internal method to set up the region manager
3667
+ _initRegionManager: function(){
3668
+ this._regionManager = new Marionette.RegionManager();
3669
+
3670
+ this.listenTo(this._regionManager, "region:add", function(name, region){
3671
+ this[name] = region;
3672
+ });
3673
+
3674
+ this.listenTo(this._regionManager, "region:remove", function(name, region){
3675
+ delete this[name];
3676
+ });
3334
3677
  }
3335
3678
  });
3336
3679
 
@@ -3374,7 +3717,7 @@ _.extend(Marionette.Module.prototype, Backbone.Events, {
3374
3717
  this._finalizerCallbacks.add(callback);
3375
3718
  },
3376
3719
 
3377
- // Start the module, and run all of it's initializers
3720
+ // Start the module, and run all of its initializers
3378
3721
  start: function(options){
3379
3722
  // Prevent re-starting a module that is already started
3380
3723
  if (this._isInitialized){ return; }
@@ -3382,11 +3725,7 @@ _.extend(Marionette.Module.prototype, Backbone.Events, {
3382
3725
  // start the sub-modules (depth-first hierarchy)
3383
3726
  _.each(this.submodules, function(mod){
3384
3727
  // check to see if we should start the sub-module with this parent
3385
- var startWithParent = true;
3386
- startWithParent = mod.startWithParent;
3387
-
3388
- // start the sub-module
3389
- if (startWithParent){
3728
+ if (mod.startWithParent){
3390
3729
  mod.start(options);
3391
3730
  }
3392
3731
  });
@@ -3440,7 +3779,7 @@ _.extend(Marionette.Module.prototype, Backbone.Events, {
3440
3779
  this.app,
3441
3780
  Backbone,
3442
3781
  Marionette,
3443
- $, _,
3782
+ Marionette.$, _,
3444
3783
  customArgs
3445
3784
  ]);
3446
3785
 
@@ -3461,12 +3800,11 @@ _.extend(Marionette.Module, {
3461
3800
 
3462
3801
  // Create a module, hanging off the app parameter as the parent object.
3463
3802
  create: function(app, moduleNames, moduleDefinition){
3464
- var that = this;
3465
3803
  var module = app;
3466
3804
 
3467
3805
  // get the custom args passed in after the module definition and
3468
3806
  // get rid of the module name and definition function
3469
- var customArgs = slice.apply(arguments);
3807
+ var customArgs = slice(arguments);
3470
3808
  customArgs.splice(0, 3);
3471
3809
 
3472
3810
  // split the module names and get the length
@@ -3480,9 +3818,9 @@ _.extend(Marionette.Module, {
3480
3818
  // Loop through all the parts of the module definition
3481
3819
  _.each(moduleNames, function(moduleName, i){
3482
3820
  var parentModule = module;
3483
- module = that._getModule(parentModule, moduleName, app);
3484
- that._addModuleDefinition(parentModule, module, moduleDefinitions[i], customArgs);
3485
- });
3821
+ module = this._getModule(parentModule, moduleName, app);
3822
+ this._addModuleDefinition(parentModule, module, moduleDefinitions[i], customArgs);
3823
+ }, this);
3486
3824
 
3487
3825
  // Return the last module in the definition chain
3488
3826
  return module;
@@ -3529,7 +3867,6 @@ _.extend(Marionette.Module, {
3529
3867
 
3530
3868
  // `and` the two together, ensuring a single `false` will prevent it
3531
3869
  // from starting with the parent
3532
- var tmp = module.startWithParent;
3533
3870
  module.startWithParent = module.startWithParent && startWithParent;
3534
3871
 
3535
3872
  // setup auto-start if needed
@@ -3553,9 +3890,10 @@ _.extend(Marionette.Module, {
3553
3890
 
3554
3891
 
3555
3892
  return Marionette;
3556
- })(Backbone, _, $ || window.jQuery || window.Zepto || window.ender);
3893
+ })(this, Backbone, _);
3894
+
3557
3895
  /*!
3558
- * Tableling v0.0.19
3896
+ * Tableling v0.0.20
3559
3897
  * Copyright (c) 2012-2013 Simon Oulevay (Alpha Hydrae) <hydrae.alpha@gmail.com>
3560
3898
  * Distributed under MIT license
3561
3899
  * https://github.com/AlphaHydrae/tableling
@@ -3563,7 +3901,7 @@ _.extend(Marionette.Module, {
3563
3901
  Backbone.Tableling = Tableling = (function(Backbone, _, $){
3564
3902
 
3565
3903
  var Tableling = {
3566
- version : "0.0.19"
3904
+ version : "0.0.20"
3567
3905
  };
3568
3906
 
3569
3907
  // Tableling