tableling-rails 0.0.21 → 0.0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,15 +1,15 @@
1
1
  ---
2
2
  !binary "U0hBMQ==":
3
3
  metadata.gz: !binary |-
4
- NmViN2FiZGUxZDhmZTQ5NDYzYjM5NzViMTUyYWFiNmFhZjZhZGEzZA==
4
+ OWM5Yzc1OGI4NzQyOWQ2MTFkZDNiYTUyOTI2MjdiY2JmYjc4MDE2Ng==
5
5
  data.tar.gz: !binary |-
6
- NjNjNWFlN2NiOTJiNGQzMjBjMWY3NDU4NzQ5NzQwNWM1NjlmMzdhMg==
6
+ OGMwZmJlZDZlMWM1ZDU4MGZjYTlmMmQwMjVmZGRkMjg4ZGI1M2QzYw==
7
7
  SHA512:
8
8
  metadata.gz: !binary |-
9
- MjQzNWI5MTliMmI1NDU4MGYxMGUwNzVmYzJhOWIxM2I2YmJkNDZiNzMxZjUz
10
- NmU1YTBiMGUzNDE3YWFiNDc4ZmQ1OWMyODRmNjYwZGFiMTYxZjg4ZGY0MDMy
11
- MzJmMDU0OTFkNTA1Nzk1NjYwYWM3ZThmNGY2NjlhNWVlMWQzY2M=
9
+ NmZhYTVhZWZlOTA5Y2MxNTM3Y2JlYmE2NTM4ZTMzODc3MzBlZTY2NjZjNWJm
10
+ MDEwNjNjNzU1NDNiODUxMTg0NjdlZjYyZDE2OGY1ODNiNDJiZmRkYzllZmYx
11
+ MzI1MDE5YjU2NWNjM2E2ZDRlMDkxYThjNTEyNzUwZDU2ZDI4NDQ=
12
12
  data.tar.gz: !binary |-
13
- Y2JiYTkyZWJhY2FjYWQ5MjJiYTljZTYxMTQyMDIxMzBkYmIyNTMxNDgwN2Fl
14
- YTY4ZDdlZDk0MzBiNWM0NTgyNDNmODdkZDhjN2FhNzQyMzBmYjExMDUwYzE0
15
- ODQxMDYwNDUxMDU3ODZmMjZkZTMyZTYxNjcyNDk3NjgxZGRiMWQ=
13
+ M2E3MzE1Mzk3OWI3NmM3ZmM5YTM2OWEzOGJlNzE5MGNjMGI1YjAwZWE5ODAw
14
+ YWRjZDIzNmMyMGZmNWMzYmE1YzM4Y2JiNzFlMjUzYjE4NzdkODk0NGRlZDNm
15
+ MmI4ZGI2NjMwNGUyNDJmZjBlYWY0MTA3OTJhNmQ4M2M5NjkwMGY=
data/VERSION CHANGED
@@ -1 +1 @@
1
- 0.0.21
1
+ 0.0.22
@@ -1,3 +1,3 @@
1
1
  module Tableling
2
- VERSION = "0.0.21"
2
+ VERSION = "0.0.22"
3
3
  end
@@ -0,0 +1,4762 @@
1
+ // Backbone.js 1.1.0
2
+
3
+ // (c) 2010-2011 Jeremy Ashkenas, DocumentCloud Inc.
4
+ // (c) 2011-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
5
+ // Backbone may be freely distributed under the MIT license.
6
+ // For all details and documentation:
7
+ // http://backbonejs.org
8
+
9
+ (function(){
10
+
11
+ // Initial Setup
12
+ // -------------
13
+
14
+ // Save a reference to the global object (`window` in the browser, `exports`
15
+ // on the server).
16
+ var root = this;
17
+
18
+ // Save the previous value of the `Backbone` variable, so that it can be
19
+ // restored later on, if `noConflict` is used.
20
+ var previousBackbone = root.Backbone;
21
+
22
+ // Create local references to array methods we'll want to use later.
23
+ var array = [];
24
+ var push = array.push;
25
+ var slice = array.slice;
26
+ var splice = array.splice;
27
+
28
+ // The top-level namespace. All public Backbone classes and modules will
29
+ // be attached to this. Exported for both the browser and the server.
30
+ var Backbone;
31
+ if (typeof exports !== 'undefined') {
32
+ Backbone = exports;
33
+ } else {
34
+ Backbone = root.Backbone = {};
35
+ }
36
+
37
+ // Current version of the library. Keep in sync with `package.json`.
38
+ Backbone.VERSION = '1.1.0';
39
+
40
+ // Require Underscore, if we're on the server, and it's not already present.
41
+ var _ = root._;
42
+ if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
43
+
44
+ // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
45
+ // the `$` variable.
46
+ Backbone.$ = root.jQuery || root.Zepto || root.ender || root.$;
47
+
48
+ // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
49
+ // to its previous owner. Returns a reference to this Backbone object.
50
+ Backbone.noConflict = function() {
51
+ root.Backbone = previousBackbone;
52
+ return this;
53
+ };
54
+
55
+ // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
56
+ // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and
57
+ // set a `X-Http-Method-Override` header.
58
+ Backbone.emulateHTTP = false;
59
+
60
+ // Turn on `emulateJSON` to support legacy servers that can't deal with direct
61
+ // `application/json` requests ... will encode the body as
62
+ // `application/x-www-form-urlencoded` instead and will send the model in a
63
+ // form param named `model`.
64
+ Backbone.emulateJSON = false;
65
+
66
+ // Backbone.Events
67
+ // ---------------
68
+
69
+ // A module that can be mixed in to *any object* in order to provide it with
70
+ // custom events. You may bind with `on` or remove with `off` callback
71
+ // functions to an event; `trigger`-ing an event fires all callbacks in
72
+ // succession.
73
+ //
74
+ // var object = {};
75
+ // _.extend(object, Backbone.Events);
76
+ // object.on('expand', function(){ alert('expanded'); });
77
+ // object.trigger('expand');
78
+ //
79
+ var Events = Backbone.Events = {
80
+
81
+ // Bind an event to a `callback` function. Passing `"all"` will bind
82
+ // the callback to all events fired.
83
+ on: function(name, callback, context) {
84
+ if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
85
+ this._events || (this._events = {});
86
+ var events = this._events[name] || (this._events[name] = []);
87
+ events.push({callback: callback, context: context, ctx: context || this});
88
+ return this;
89
+ },
90
+
91
+ // Bind an event to only be triggered a single time. After the first time
92
+ // the callback is invoked, it will be removed.
93
+ once: function(name, callback, context) {
94
+ if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this;
95
+ var self = this;
96
+ var once = _.once(function() {
97
+ self.off(name, once);
98
+ callback.apply(this, arguments);
99
+ });
100
+ once._callback = callback;
101
+ return this.on(name, once, context);
102
+ },
103
+
104
+ // Remove one or many callbacks. If `context` is null, removes all
105
+ // callbacks with that function. If `callback` is null, removes all
106
+ // callbacks for the event. If `name` is null, removes all bound
107
+ // callbacks for all events.
108
+ off: function(name, callback, context) {
109
+ var retain, ev, events, names, i, l, j, k;
110
+ if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
111
+ if (!name && !callback && !context) {
112
+ this._events = {};
113
+ return this;
114
+ }
115
+ names = name ? [name] : _.keys(this._events);
116
+ for (i = 0, l = names.length; i < l; i++) {
117
+ name = names[i];
118
+ if (events = this._events[name]) {
119
+ this._events[name] = retain = [];
120
+ if (callback || context) {
121
+ for (j = 0, k = events.length; j < k; j++) {
122
+ ev = events[j];
123
+ if ((callback && callback !== ev.callback && callback !== ev.callback._callback) ||
124
+ (context && context !== ev.context)) {
125
+ retain.push(ev);
126
+ }
127
+ }
128
+ }
129
+ if (!retain.length) delete this._events[name];
130
+ }
131
+ }
132
+
133
+ return this;
134
+ },
135
+
136
+ // Trigger one or many events, firing all bound callbacks. Callbacks are
137
+ // passed the same arguments as `trigger` is, apart from the event name
138
+ // (unless you're listening on `"all"`, which will cause your callback to
139
+ // receive the true name of the event as the first argument).
140
+ trigger: function(name) {
141
+ if (!this._events) return this;
142
+ var args = slice.call(arguments, 1);
143
+ if (!eventsApi(this, 'trigger', name, args)) return this;
144
+ var events = this._events[name];
145
+ var allEvents = this._events.all;
146
+ if (events) triggerEvents(events, args);
147
+ if (allEvents) triggerEvents(allEvents, arguments);
148
+ return this;
149
+ },
150
+
151
+ // Tell this object to stop listening to either specific events ... or
152
+ // to every object it's currently listening to.
153
+ stopListening: function(obj, name, callback) {
154
+ var listeningTo = this._listeningTo;
155
+ if (!listeningTo) return this;
156
+ var remove = !name && !callback;
157
+ if (!callback && typeof name === 'object') callback = this;
158
+ if (obj) (listeningTo = {})[obj._listenId] = obj;
159
+ for (var id in listeningTo) {
160
+ obj = listeningTo[id];
161
+ obj.off(name, callback, this);
162
+ if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id];
163
+ }
164
+ return this;
165
+ }
166
+
167
+ };
168
+
169
+ // Regular expression used to split event strings.
170
+ var eventSplitter = /\s+/;
171
+
172
+ // Implement fancy features of the Events API such as multiple event
173
+ // names `"change blur"` and jQuery-style event maps `{change: action}`
174
+ // in terms of the existing API.
175
+ var eventsApi = function(obj, action, name, rest) {
176
+ if (!name) return true;
177
+
178
+ // Handle event maps.
179
+ if (typeof name === 'object') {
180
+ for (var key in name) {
181
+ obj[action].apply(obj, [key, name[key]].concat(rest));
182
+ }
183
+ return false;
184
+ }
185
+
186
+ // Handle space separated event names.
187
+ if (eventSplitter.test(name)) {
188
+ var names = name.split(eventSplitter);
189
+ for (var i = 0, l = names.length; i < l; i++) {
190
+ obj[action].apply(obj, [names[i]].concat(rest));
191
+ }
192
+ return false;
193
+ }
194
+
195
+ return true;
196
+ };
197
+
198
+ // A difficult-to-believe, but optimized internal dispatch function for
199
+ // triggering events. Tries to keep the usual cases speedy (most internal
200
+ // Backbone events have 3 arguments).
201
+ var triggerEvents = function(events, args) {
202
+ var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
203
+ switch (args.length) {
204
+ case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
205
+ case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
206
+ case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
207
+ case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
208
+ default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
209
+ }
210
+ };
211
+
212
+ var listenMethods = {listenTo: 'on', listenToOnce: 'once'};
213
+
214
+ // Inversion-of-control versions of `on` and `once`. Tell *this* object to
215
+ // listen to an event in another object ... keeping track of what it's
216
+ // listening to.
217
+ _.each(listenMethods, function(implementation, method) {
218
+ Events[method] = function(obj, name, callback) {
219
+ var listeningTo = this._listeningTo || (this._listeningTo = {});
220
+ var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
221
+ listeningTo[id] = obj;
222
+ if (!callback && typeof name === 'object') callback = this;
223
+ obj[implementation](name, callback, this);
224
+ return this;
225
+ };
226
+ });
227
+
228
+ // Aliases for backwards compatibility.
229
+ Events.bind = Events.on;
230
+ Events.unbind = Events.off;
231
+
232
+ // Allow the `Backbone` object to serve as a global event bus, for folks who
233
+ // want global "pubsub" in a convenient place.
234
+ _.extend(Backbone, Events);
235
+
236
+ // Backbone.Model
237
+ // --------------
238
+
239
+ // Backbone **Models** are the basic data object in the framework --
240
+ // frequently representing a row in a table in a database on your server.
241
+ // A discrete chunk of data and a bunch of useful, related methods for
242
+ // performing computations and transformations on that data.
243
+
244
+ // Create a new model with the specified attributes. A client id (`cid`)
245
+ // is automatically generated and assigned for you.
246
+ var Model = Backbone.Model = function(attributes, options) {
247
+ var attrs = attributes || {};
248
+ options || (options = {});
249
+ this.cid = _.uniqueId('c');
250
+ this.attributes = {};
251
+ if (options.collection) this.collection = options.collection;
252
+ if (options.parse) attrs = this.parse(attrs, options) || {};
253
+ attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
254
+ this.set(attrs, options);
255
+ this.changed = {};
256
+ this.initialize.apply(this, arguments);
257
+ };
258
+
259
+ // Attach all inheritable methods to the Model prototype.
260
+ _.extend(Model.prototype, Events, {
261
+
262
+ // A hash of attributes whose current and previous value differ.
263
+ changed: null,
264
+
265
+ // The value returned during the last failed validation.
266
+ validationError: null,
267
+
268
+ // The default name for the JSON `id` attribute is `"id"`. MongoDB and
269
+ // CouchDB users may want to set this to `"_id"`.
270
+ idAttribute: 'id',
271
+
272
+ // Initialize is an empty function by default. Override it with your own
273
+ // initialization logic.
274
+ initialize: function(){},
275
+
276
+ // Return a copy of the model's `attributes` object.
277
+ toJSON: function(options) {
278
+ return _.clone(this.attributes);
279
+ },
280
+
281
+ // Proxy `Backbone.sync` by default -- but override this if you need
282
+ // custom syncing semantics for *this* particular model.
283
+ sync: function() {
284
+ return Backbone.sync.apply(this, arguments);
285
+ },
286
+
287
+ // Get the value of an attribute.
288
+ get: function(attr) {
289
+ return this.attributes[attr];
290
+ },
291
+
292
+ // Get the HTML-escaped value of an attribute.
293
+ escape: function(attr) {
294
+ return _.escape(this.get(attr));
295
+ },
296
+
297
+ // Returns `true` if the attribute contains a value that is not null
298
+ // or undefined.
299
+ has: function(attr) {
300
+ return this.get(attr) != null;
301
+ },
302
+
303
+ // Set a hash of model attributes on the object, firing `"change"`. This is
304
+ // the core primitive operation of a model, updating the data and notifying
305
+ // anyone who needs to know about the change in state. The heart of the beast.
306
+ set: function(key, val, options) {
307
+ var attr, attrs, unset, changes, silent, changing, prev, current;
308
+ if (key == null) return this;
309
+
310
+ // Handle both `"key", value` and `{key: value}` -style arguments.
311
+ if (typeof key === 'object') {
312
+ attrs = key;
313
+ options = val;
314
+ } else {
315
+ (attrs = {})[key] = val;
316
+ }
317
+
318
+ options || (options = {});
319
+
320
+ // Run validation.
321
+ if (!this._validate(attrs, options)) return false;
322
+
323
+ // Extract attributes and options.
324
+ unset = options.unset;
325
+ silent = options.silent;
326
+ changes = [];
327
+ changing = this._changing;
328
+ this._changing = true;
329
+
330
+ if (!changing) {
331
+ this._previousAttributes = _.clone(this.attributes);
332
+ this.changed = {};
333
+ }
334
+ current = this.attributes, prev = this._previousAttributes;
335
+
336
+ // Check for changes of `id`.
337
+ if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
338
+
339
+ // For each `set` attribute, update or delete the current value.
340
+ for (attr in attrs) {
341
+ val = attrs[attr];
342
+ if (!_.isEqual(current[attr], val)) changes.push(attr);
343
+ if (!_.isEqual(prev[attr], val)) {
344
+ this.changed[attr] = val;
345
+ } else {
346
+ delete this.changed[attr];
347
+ }
348
+ unset ? delete current[attr] : current[attr] = val;
349
+ }
350
+
351
+ // Trigger all relevant attribute changes.
352
+ if (!silent) {
353
+ if (changes.length) this._pending = true;
354
+ for (var i = 0, l = changes.length; i < l; i++) {
355
+ this.trigger('change:' + changes[i], this, current[changes[i]], options);
356
+ }
357
+ }
358
+
359
+ // You might be wondering why there's a `while` loop here. Changes can
360
+ // be recursively nested within `"change"` events.
361
+ if (changing) return this;
362
+ if (!silent) {
363
+ while (this._pending) {
364
+ this._pending = false;
365
+ this.trigger('change', this, options);
366
+ }
367
+ }
368
+ this._pending = false;
369
+ this._changing = false;
370
+ return this;
371
+ },
372
+
373
+ // Remove an attribute from the model, firing `"change"`. `unset` is a noop
374
+ // if the attribute doesn't exist.
375
+ unset: function(attr, options) {
376
+ return this.set(attr, void 0, _.extend({}, options, {unset: true}));
377
+ },
378
+
379
+ // Clear all attributes on the model, firing `"change"`.
380
+ clear: function(options) {
381
+ var attrs = {};
382
+ for (var key in this.attributes) attrs[key] = void 0;
383
+ return this.set(attrs, _.extend({}, options, {unset: true}));
384
+ },
385
+
386
+ // Determine if the model has changed since the last `"change"` event.
387
+ // If you specify an attribute name, determine if that attribute has changed.
388
+ hasChanged: function(attr) {
389
+ if (attr == null) return !_.isEmpty(this.changed);
390
+ return _.has(this.changed, attr);
391
+ },
392
+
393
+ // Return an object containing all the attributes that have changed, or
394
+ // false if there are no changed attributes. Useful for determining what
395
+ // parts of a view need to be updated and/or what attributes need to be
396
+ // persisted to the server. Unset attributes will be set to undefined.
397
+ // You can also pass an attributes object to diff against the model,
398
+ // determining if there *would be* a change.
399
+ changedAttributes: function(diff) {
400
+ if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
401
+ var val, changed = false;
402
+ var old = this._changing ? this._previousAttributes : this.attributes;
403
+ for (var attr in diff) {
404
+ if (_.isEqual(old[attr], (val = diff[attr]))) continue;
405
+ (changed || (changed = {}))[attr] = val;
406
+ }
407
+ return changed;
408
+ },
409
+
410
+ // Get the previous value of an attribute, recorded at the time the last
411
+ // `"change"` event was fired.
412
+ previous: function(attr) {
413
+ if (attr == null || !this._previousAttributes) return null;
414
+ return this._previousAttributes[attr];
415
+ },
416
+
417
+ // Get all of the attributes of the model at the time of the previous
418
+ // `"change"` event.
419
+ previousAttributes: function() {
420
+ return _.clone(this._previousAttributes);
421
+ },
422
+
423
+ // Fetch the model from the server. If the server's representation of the
424
+ // model differs from its current attributes, they will be overridden,
425
+ // triggering a `"change"` event.
426
+ fetch: function(options) {
427
+ options = options ? _.clone(options) : {};
428
+ if (options.parse === void 0) options.parse = true;
429
+ var model = this;
430
+ var success = options.success;
431
+ options.success = function(resp) {
432
+ if (!model.set(model.parse(resp, options), options)) return false;
433
+ if (success) success(model, resp, options);
434
+ model.trigger('sync', model, resp, options);
435
+ };
436
+ wrapError(this, options);
437
+ return this.sync('read', this, options);
438
+ },
439
+
440
+ // Set a hash of model attributes, and sync the model to the server.
441
+ // If the server returns an attributes hash that differs, the model's
442
+ // state will be `set` again.
443
+ save: function(key, val, options) {
444
+ var attrs, method, xhr, attributes = this.attributes;
445
+
446
+ // Handle both `"key", value` and `{key: value}` -style arguments.
447
+ if (key == null || typeof key === 'object') {
448
+ attrs = key;
449
+ options = val;
450
+ } else {
451
+ (attrs = {})[key] = val;
452
+ }
453
+
454
+ options = _.extend({validate: true}, options);
455
+
456
+ // If we're not waiting and attributes exist, save acts as
457
+ // `set(attr).save(null, opts)` with validation. Otherwise, check if
458
+ // the model will be valid when the attributes, if any, are set.
459
+ if (attrs && !options.wait) {
460
+ if (!this.set(attrs, options)) return false;
461
+ } else {
462
+ if (!this._validate(attrs, options)) return false;
463
+ }
464
+
465
+ // Set temporary attributes if `{wait: true}`.
466
+ if (attrs && options.wait) {
467
+ this.attributes = _.extend({}, attributes, attrs);
468
+ }
469
+
470
+ // After a successful server-side save, the client is (optionally)
471
+ // updated with the server-side state.
472
+ if (options.parse === void 0) options.parse = true;
473
+ var model = this;
474
+ var success = options.success;
475
+ options.success = function(resp) {
476
+ // Ensure attributes are restored during synchronous saves.
477
+ model.attributes = attributes;
478
+ var serverAttrs = model.parse(resp, options);
479
+ if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
480
+ if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
481
+ return false;
482
+ }
483
+ if (success) success(model, resp, options);
484
+ model.trigger('sync', model, resp, options);
485
+ };
486
+ wrapError(this, options);
487
+
488
+ method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
489
+ if (method === 'patch') options.attrs = attrs;
490
+ xhr = this.sync(method, this, options);
491
+
492
+ // Restore attributes.
493
+ if (attrs && options.wait) this.attributes = attributes;
494
+
495
+ return xhr;
496
+ },
497
+
498
+ // Destroy this model on the server if it was already persisted.
499
+ // Optimistically removes the model from its collection, if it has one.
500
+ // If `wait: true` is passed, waits for the server to respond before removal.
501
+ destroy: function(options) {
502
+ options = options ? _.clone(options) : {};
503
+ var model = this;
504
+ var success = options.success;
505
+
506
+ var destroy = function() {
507
+ model.trigger('destroy', model, model.collection, options);
508
+ };
509
+
510
+ options.success = function(resp) {
511
+ if (options.wait || model.isNew()) destroy();
512
+ if (success) success(model, resp, options);
513
+ if (!model.isNew()) model.trigger('sync', model, resp, options);
514
+ };
515
+
516
+ if (this.isNew()) {
517
+ options.success();
518
+ return false;
519
+ }
520
+ wrapError(this, options);
521
+
522
+ var xhr = this.sync('delete', this, options);
523
+ if (!options.wait) destroy();
524
+ return xhr;
525
+ },
526
+
527
+ // Default URL for the model's representation on the server -- if you're
528
+ // using Backbone's restful methods, override this to change the endpoint
529
+ // that will be called.
530
+ url: function() {
531
+ var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError();
532
+ if (this.isNew()) return base;
533
+ return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id);
534
+ },
535
+
536
+ // **parse** converts a response into the hash of attributes to be `set` on
537
+ // the model. The default implementation is just to pass the response along.
538
+ parse: function(resp, options) {
539
+ return resp;
540
+ },
541
+
542
+ // Create a new model with identical attributes to this one.
543
+ clone: function() {
544
+ return new this.constructor(this.attributes);
545
+ },
546
+
547
+ // A model is new if it has never been saved to the server, and lacks an id.
548
+ isNew: function() {
549
+ return this.id == null;
550
+ },
551
+
552
+ // Check if the model is currently in a valid state.
553
+ isValid: function(options) {
554
+ return this._validate({}, _.extend(options || {}, { validate: true }));
555
+ },
556
+
557
+ // Run validation against the next complete set of model attributes,
558
+ // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
559
+ _validate: function(attrs, options) {
560
+ if (!options.validate || !this.validate) return true;
561
+ attrs = _.extend({}, this.attributes, attrs);
562
+ var error = this.validationError = this.validate(attrs, options) || null;
563
+ if (!error) return true;
564
+ this.trigger('invalid', this, error, _.extend(options, {validationError: error}));
565
+ return false;
566
+ }
567
+
568
+ });
569
+
570
+ // Underscore methods that we want to implement on the Model.
571
+ var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'];
572
+
573
+ // Mix in each Underscore method as a proxy to `Model#attributes`.
574
+ _.each(modelMethods, function(method) {
575
+ Model.prototype[method] = function() {
576
+ var args = slice.call(arguments);
577
+ args.unshift(this.attributes);
578
+ return _[method].apply(_, args);
579
+ };
580
+ });
581
+
582
+ // Backbone.Collection
583
+ // -------------------
584
+
585
+ // If models tend to represent a single row of data, a Backbone Collection is
586
+ // more analagous to a table full of data ... or a small slice or page of that
587
+ // table, or a collection of rows that belong together for a particular reason
588
+ // -- all of the messages in this particular folder, all of the documents
589
+ // belonging to this particular author, and so on. Collections maintain
590
+ // indexes of their models, both in order, and for lookup by `id`.
591
+
592
+ // Create a new **Collection**, perhaps to contain a specific type of `model`.
593
+ // If a `comparator` is specified, the Collection will maintain
594
+ // its models in sort order, as they're added and removed.
595
+ var Collection = Backbone.Collection = function(models, options) {
596
+ options || (options = {});
597
+ if (options.model) this.model = options.model;
598
+ if (options.comparator !== void 0) this.comparator = options.comparator;
599
+ this._reset();
600
+ this.initialize.apply(this, arguments);
601
+ if (models) this.reset(models, _.extend({silent: true}, options));
602
+ };
603
+
604
+ // Default options for `Collection#set`.
605
+ var setOptions = {add: true, remove: true, merge: true};
606
+ var addOptions = {add: true, remove: false};
607
+
608
+ // Define the Collection's inheritable methods.
609
+ _.extend(Collection.prototype, Events, {
610
+
611
+ // The default model for a collection is just a **Backbone.Model**.
612
+ // This should be overridden in most cases.
613
+ model: Model,
614
+
615
+ // Initialize is an empty function by default. Override it with your own
616
+ // initialization logic.
617
+ initialize: function(){},
618
+
619
+ // The JSON representation of a Collection is an array of the
620
+ // models' attributes.
621
+ toJSON: function(options) {
622
+ return this.map(function(model){ return model.toJSON(options); });
623
+ },
624
+
625
+ // Proxy `Backbone.sync` by default.
626
+ sync: function() {
627
+ return Backbone.sync.apply(this, arguments);
628
+ },
629
+
630
+ // Add a model, or list of models to the set.
631
+ add: function(models, options) {
632
+ return this.set(models, _.extend({merge: false}, options, addOptions));
633
+ },
634
+
635
+ // Remove a model, or a list of models from the set.
636
+ remove: function(models, options) {
637
+ var singular = !_.isArray(models);
638
+ models = singular ? [models] : _.clone(models);
639
+ options || (options = {});
640
+ var i, l, index, model;
641
+ for (i = 0, l = models.length; i < l; i++) {
642
+ model = models[i] = this.get(models[i]);
643
+ if (!model) continue;
644
+ delete this._byId[model.id];
645
+ delete this._byId[model.cid];
646
+ index = this.indexOf(model);
647
+ this.models.splice(index, 1);
648
+ this.length--;
649
+ if (!options.silent) {
650
+ options.index = index;
651
+ model.trigger('remove', model, this, options);
652
+ }
653
+ this._removeReference(model);
654
+ }
655
+ return singular ? models[0] : models;
656
+ },
657
+
658
+ // Update a collection by `set`-ing a new list of models, adding new ones,
659
+ // removing models that are no longer present, and merging models that
660
+ // already exist in the collection, as necessary. Similar to **Model#set**,
661
+ // the core operation for updating the data contained by the collection.
662
+ set: function(models, options) {
663
+ options = _.defaults({}, options, setOptions);
664
+ if (options.parse) models = this.parse(models, options);
665
+ var singular = !_.isArray(models);
666
+ models = singular ? (models ? [models] : []) : _.clone(models);
667
+ var i, l, id, model, attrs, existing, sort;
668
+ var at = options.at;
669
+ var targetModel = this.model;
670
+ var sortable = this.comparator && (at == null) && options.sort !== false;
671
+ var sortAttr = _.isString(this.comparator) ? this.comparator : null;
672
+ var toAdd = [], toRemove = [], modelMap = {};
673
+ var add = options.add, merge = options.merge, remove = options.remove;
674
+ var order = !sortable && add && remove ? [] : false;
675
+
676
+ // Turn bare objects into model references, and prevent invalid models
677
+ // from being added.
678
+ for (i = 0, l = models.length; i < l; i++) {
679
+ attrs = models[i];
680
+ if (attrs instanceof Model) {
681
+ id = model = attrs;
682
+ } else {
683
+ id = attrs[targetModel.prototype.idAttribute];
684
+ }
685
+
686
+ // If a duplicate is found, prevent it from being added and
687
+ // optionally merge it into the existing model.
688
+ if (existing = this.get(id)) {
689
+ if (remove) modelMap[existing.cid] = true;
690
+ if (merge) {
691
+ attrs = attrs === model ? model.attributes : attrs;
692
+ if (options.parse) attrs = existing.parse(attrs, options);
693
+ existing.set(attrs, options);
694
+ if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
695
+ }
696
+ models[i] = existing;
697
+
698
+ // If this is a new, valid model, push it to the `toAdd` list.
699
+ } else if (add) {
700
+ model = models[i] = this._prepareModel(attrs, options);
701
+ if (!model) continue;
702
+ toAdd.push(model);
703
+
704
+ // Listen to added models' events, and index models for lookup by
705
+ // `id` and by `cid`.
706
+ model.on('all', this._onModelEvent, this);
707
+ this._byId[model.cid] = model;
708
+ if (model.id != null) this._byId[model.id] = model;
709
+ }
710
+ if (order) order.push(existing || model);
711
+ }
712
+
713
+ // Remove nonexistent models if appropriate.
714
+ if (remove) {
715
+ for (i = 0, l = this.length; i < l; ++i) {
716
+ if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model);
717
+ }
718
+ if (toRemove.length) this.remove(toRemove, options);
719
+ }
720
+
721
+ // See if sorting is needed, update `length` and splice in new models.
722
+ if (toAdd.length || (order && order.length)) {
723
+ if (sortable) sort = true;
724
+ this.length += toAdd.length;
725
+ if (at != null) {
726
+ for (i = 0, l = toAdd.length; i < l; i++) {
727
+ this.models.splice(at + i, 0, toAdd[i]);
728
+ }
729
+ } else {
730
+ if (order) this.models.length = 0;
731
+ var orderedModels = order || toAdd;
732
+ for (i = 0, l = orderedModels.length; i < l; i++) {
733
+ this.models.push(orderedModels[i]);
734
+ }
735
+ }
736
+ }
737
+
738
+ // Silently sort the collection if appropriate.
739
+ if (sort) this.sort({silent: true});
740
+
741
+ // Unless silenced, it's time to fire all appropriate add/sort events.
742
+ if (!options.silent) {
743
+ for (i = 0, l = toAdd.length; i < l; i++) {
744
+ (model = toAdd[i]).trigger('add', model, this, options);
745
+ }
746
+ if (sort || (order && order.length)) this.trigger('sort', this, options);
747
+ }
748
+
749
+ // Return the added (or merged) model (or models).
750
+ return singular ? models[0] : models;
751
+ },
752
+
753
+ // When you have more items than you want to add or remove individually,
754
+ // you can reset the entire set with a new list of models, without firing
755
+ // any granular `add` or `remove` events. Fires `reset` when finished.
756
+ // Useful for bulk operations and optimizations.
757
+ reset: function(models, options) {
758
+ options || (options = {});
759
+ for (var i = 0, l = this.models.length; i < l; i++) {
760
+ this._removeReference(this.models[i]);
761
+ }
762
+ options.previousModels = this.models;
763
+ this._reset();
764
+ models = this.add(models, _.extend({silent: true}, options));
765
+ if (!options.silent) this.trigger('reset', this, options);
766
+ return models;
767
+ },
768
+
769
+ // Add a model to the end of the collection.
770
+ push: function(model, options) {
771
+ return this.add(model, _.extend({at: this.length}, options));
772
+ },
773
+
774
+ // Remove a model from the end of the collection.
775
+ pop: function(options) {
776
+ var model = this.at(this.length - 1);
777
+ this.remove(model, options);
778
+ return model;
779
+ },
780
+
781
+ // Add a model to the beginning of the collection.
782
+ unshift: function(model, options) {
783
+ return this.add(model, _.extend({at: 0}, options));
784
+ },
785
+
786
+ // Remove a model from the beginning of the collection.
787
+ shift: function(options) {
788
+ var model = this.at(0);
789
+ this.remove(model, options);
790
+ return model;
791
+ },
792
+
793
+ // Slice out a sub-array of models from the collection.
794
+ slice: function() {
795
+ return slice.apply(this.models, arguments);
796
+ },
797
+
798
+ // Get a model from the set by id.
799
+ get: function(obj) {
800
+ if (obj == null) return void 0;
801
+ return this._byId[obj.id] || this._byId[obj.cid] || this._byId[obj];
802
+ },
803
+
804
+ // Get the model at the given index.
805
+ at: function(index) {
806
+ return this.models[index];
807
+ },
808
+
809
+ // Return models with matching attributes. Useful for simple cases of
810
+ // `filter`.
811
+ where: function(attrs, first) {
812
+ if (_.isEmpty(attrs)) return first ? void 0 : [];
813
+ return this[first ? 'find' : 'filter'](function(model) {
814
+ for (var key in attrs) {
815
+ if (attrs[key] !== model.get(key)) return false;
816
+ }
817
+ return true;
818
+ });
819
+ },
820
+
821
+ // Return the first model with matching attributes. Useful for simple cases
822
+ // of `find`.
823
+ findWhere: function(attrs) {
824
+ return this.where(attrs, true);
825
+ },
826
+
827
+ // Force the collection to re-sort itself. You don't need to call this under
828
+ // normal circumstances, as the set will maintain sort order as each item
829
+ // is added.
830
+ sort: function(options) {
831
+ if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
832
+ options || (options = {});
833
+
834
+ // Run sort based on type of `comparator`.
835
+ if (_.isString(this.comparator) || this.comparator.length === 1) {
836
+ this.models = this.sortBy(this.comparator, this);
837
+ } else {
838
+ this.models.sort(_.bind(this.comparator, this));
839
+ }
840
+
841
+ if (!options.silent) this.trigger('sort', this, options);
842
+ return this;
843
+ },
844
+
845
+ // Pluck an attribute from each model in the collection.
846
+ pluck: function(attr) {
847
+ return _.invoke(this.models, 'get', attr);
848
+ },
849
+
850
+ // Fetch the default set of models for this collection, resetting the
851
+ // collection when they arrive. If `reset: true` is passed, the response
852
+ // data will be passed through the `reset` method instead of `set`.
853
+ fetch: function(options) {
854
+ options = options ? _.clone(options) : {};
855
+ if (options.parse === void 0) options.parse = true;
856
+ var success = options.success;
857
+ var collection = this;
858
+ options.success = function(resp) {
859
+ var method = options.reset ? 'reset' : 'set';
860
+ collection[method](resp, options);
861
+ if (success) success(collection, resp, options);
862
+ collection.trigger('sync', collection, resp, options);
863
+ };
864
+ wrapError(this, options);
865
+ return this.sync('read', this, options);
866
+ },
867
+
868
+ // Create a new instance of a model in this collection. Add the model to the
869
+ // collection immediately, unless `wait: true` is passed, in which case we
870
+ // wait for the server to agree.
871
+ create: function(model, options) {
872
+ options = options ? _.clone(options) : {};
873
+ if (!(model = this._prepareModel(model, options))) return false;
874
+ if (!options.wait) this.add(model, options);
875
+ var collection = this;
876
+ var success = options.success;
877
+ options.success = function(model, resp, options) {
878
+ if (options.wait) collection.add(model, options);
879
+ if (success) success(model, resp, options);
880
+ };
881
+ model.save(null, options);
882
+ return model;
883
+ },
884
+
885
+ // **parse** converts a response into a list of models to be added to the
886
+ // collection. The default implementation is just to pass it through.
887
+ parse: function(resp, options) {
888
+ return resp;
889
+ },
890
+
891
+ // Create a new collection with an identical list of models as this one.
892
+ clone: function() {
893
+ return new this.constructor(this.models);
894
+ },
895
+
896
+ // Private method to reset all internal state. Called when the collection
897
+ // is first initialized or reset.
898
+ _reset: function() {
899
+ this.length = 0;
900
+ this.models = [];
901
+ this._byId = {};
902
+ },
903
+
904
+ // Prepare a hash of attributes (or other model) to be added to this
905
+ // collection.
906
+ _prepareModel: function(attrs, options) {
907
+ if (attrs instanceof Model) {
908
+ if (!attrs.collection) attrs.collection = this;
909
+ return attrs;
910
+ }
911
+ options = options ? _.clone(options) : {};
912
+ options.collection = this;
913
+ var model = new this.model(attrs, options);
914
+ if (!model.validationError) return model;
915
+ this.trigger('invalid', this, model.validationError, options);
916
+ return false;
917
+ },
918
+
919
+ // Internal method to sever a model's ties to a collection.
920
+ _removeReference: function(model) {
921
+ if (this === model.collection) delete model.collection;
922
+ model.off('all', this._onModelEvent, this);
923
+ },
924
+
925
+ // Internal method called every time a model in the set fires an event.
926
+ // Sets need to update their indexes when models change ids. All other
927
+ // events simply proxy through. "add" and "remove" events that originate
928
+ // in other collections are ignored.
929
+ _onModelEvent: function(event, model, collection, options) {
930
+ if ((event === 'add' || event === 'remove') && collection !== this) return;
931
+ if (event === 'destroy') this.remove(model, options);
932
+ if (model && event === 'change:' + model.idAttribute) {
933
+ delete this._byId[model.previous(model.idAttribute)];
934
+ if (model.id != null) this._byId[model.id] = model;
935
+ }
936
+ this.trigger.apply(this, arguments);
937
+ }
938
+
939
+ });
940
+
941
+ // Underscore methods that we want to implement on the Collection.
942
+ // 90% of the core usefulness of Backbone Collections is actually implemented
943
+ // right here:
944
+ var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
945
+ 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
946
+ 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
947
+ 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest',
948
+ 'tail', 'drop', 'last', 'without', 'difference', 'indexOf', 'shuffle',
949
+ 'lastIndexOf', 'isEmpty', 'chain'];
950
+
951
+ // Mix in each Underscore method as a proxy to `Collection#models`.
952
+ _.each(methods, function(method) {
953
+ Collection.prototype[method] = function() {
954
+ var args = slice.call(arguments);
955
+ args.unshift(this.models);
956
+ return _[method].apply(_, args);
957
+ };
958
+ });
959
+
960
+ // Underscore methods that take a property name as an argument.
961
+ var attributeMethods = ['groupBy', 'countBy', 'sortBy'];
962
+
963
+ // Use attributes instead of properties.
964
+ _.each(attributeMethods, function(method) {
965
+ Collection.prototype[method] = function(value, context) {
966
+ var iterator = _.isFunction(value) ? value : function(model) {
967
+ return model.get(value);
968
+ };
969
+ return _[method](this.models, iterator, context);
970
+ };
971
+ });
972
+
973
+ // Backbone.View
974
+ // -------------
975
+
976
+ // Backbone Views are almost more convention than they are actual code. A View
977
+ // is simply a JavaScript object that represents a logical chunk of UI in the
978
+ // DOM. This might be a single item, an entire list, a sidebar or panel, or
979
+ // even the surrounding frame which wraps your whole app. Defining a chunk of
980
+ // UI as a **View** allows you to define your DOM events declaratively, without
981
+ // having to worry about render order ... and makes it easy for the view to
982
+ // react to specific changes in the state of your models.
983
+
984
+ // Creating a Backbone.View creates its initial element outside of the DOM,
985
+ // if an existing element is not provided...
986
+ var View = Backbone.View = function(options) {
987
+ this.cid = _.uniqueId('view');
988
+ options || (options = {});
989
+ _.extend(this, _.pick(options, viewOptions));
990
+ this._ensureElement();
991
+ this.initialize.apply(this, arguments);
992
+ this.delegateEvents();
993
+ };
994
+
995
+ // Cached regex to split keys for `delegate`.
996
+ var delegateEventSplitter = /^(\S+)\s*(.*)$/;
997
+
998
+ // List of view options to be merged as properties.
999
+ var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
1000
+
1001
+ // Set up all inheritable **Backbone.View** properties and methods.
1002
+ _.extend(View.prototype, Events, {
1003
+
1004
+ // The default `tagName` of a View's element is `"div"`.
1005
+ tagName: 'div',
1006
+
1007
+ // jQuery delegate for element lookup, scoped to DOM elements within the
1008
+ // current view. This should be preferred to global lookups where possible.
1009
+ $: function(selector) {
1010
+ return this.$el.find(selector);
1011
+ },
1012
+
1013
+ // Initialize is an empty function by default. Override it with your own
1014
+ // initialization logic.
1015
+ initialize: function(){},
1016
+
1017
+ // **render** is the core function that your view should override, in order
1018
+ // to populate its element (`this.el`), with the appropriate HTML. The
1019
+ // convention is for **render** to always return `this`.
1020
+ render: function() {
1021
+ return this;
1022
+ },
1023
+
1024
+ // Remove this view by taking the element out of the DOM, and removing any
1025
+ // applicable Backbone.Events listeners.
1026
+ remove: function() {
1027
+ this.$el.remove();
1028
+ this.stopListening();
1029
+ return this;
1030
+ },
1031
+
1032
+ // Change the view's element (`this.el` property), including event
1033
+ // re-delegation.
1034
+ setElement: function(element, delegate) {
1035
+ if (this.$el) this.undelegateEvents();
1036
+ this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
1037
+ this.el = this.$el[0];
1038
+ if (delegate !== false) this.delegateEvents();
1039
+ return this;
1040
+ },
1041
+
1042
+ // Set callbacks, where `this.events` is a hash of
1043
+ //
1044
+ // *{"event selector": "callback"}*
1045
+ //
1046
+ // {
1047
+ // 'mousedown .title': 'edit',
1048
+ // 'click .button': 'save',
1049
+ // 'click .open': function(e) { ... }
1050
+ // }
1051
+ //
1052
+ // pairs. Callbacks will be bound to the view, with `this` set properly.
1053
+ // Uses event delegation for efficiency.
1054
+ // Omitting the selector binds the event to `this.el`.
1055
+ // This only works for delegate-able events: not `focus`, `blur`, and
1056
+ // not `change`, `submit`, and `reset` in Internet Explorer.
1057
+ delegateEvents: function(events) {
1058
+ if (!(events || (events = _.result(this, 'events')))) return this;
1059
+ this.undelegateEvents();
1060
+ for (var key in events) {
1061
+ var method = events[key];
1062
+ if (!_.isFunction(method)) method = this[events[key]];
1063
+ if (!method) continue;
1064
+
1065
+ var match = key.match(delegateEventSplitter);
1066
+ var eventName = match[1], selector = match[2];
1067
+ method = _.bind(method, this);
1068
+ eventName += '.delegateEvents' + this.cid;
1069
+ if (selector === '') {
1070
+ this.$el.on(eventName, method);
1071
+ } else {
1072
+ this.$el.on(eventName, selector, method);
1073
+ }
1074
+ }
1075
+ return this;
1076
+ },
1077
+
1078
+ // Clears all callbacks previously bound to the view with `delegateEvents`.
1079
+ // You usually don't need to use this, but may wish to if you have multiple
1080
+ // Backbone views attached to the same DOM element.
1081
+ undelegateEvents: function() {
1082
+ this.$el.off('.delegateEvents' + this.cid);
1083
+ return this;
1084
+ },
1085
+
1086
+ // Ensure that the View has a DOM element to render into.
1087
+ // If `this.el` is a string, pass it through `$()`, take the first
1088
+ // matching element, and re-assign it to `el`. Otherwise, create
1089
+ // an element from the `id`, `className` and `tagName` properties.
1090
+ _ensureElement: function() {
1091
+ if (!this.el) {
1092
+ var attrs = _.extend({}, _.result(this, 'attributes'));
1093
+ if (this.id) attrs.id = _.result(this, 'id');
1094
+ if (this.className) attrs['class'] = _.result(this, 'className');
1095
+ var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
1096
+ this.setElement($el, false);
1097
+ } else {
1098
+ this.setElement(_.result(this, 'el'), false);
1099
+ }
1100
+ }
1101
+
1102
+ });
1103
+
1104
+ // Backbone.sync
1105
+ // -------------
1106
+
1107
+ // Override this function to change the manner in which Backbone persists
1108
+ // models to the server. You will be passed the type of request, and the
1109
+ // model in question. By default, makes a RESTful Ajax request
1110
+ // to the model's `url()`. Some possible customizations could be:
1111
+ //
1112
+ // * Use `setTimeout` to batch rapid-fire updates into a single request.
1113
+ // * Send up the models as XML instead of JSON.
1114
+ // * Persist models via WebSockets instead of Ajax.
1115
+ //
1116
+ // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
1117
+ // as `POST`, with a `_method` parameter containing the true HTTP method,
1118
+ // as well as all requests with the body as `application/x-www-form-urlencoded`
1119
+ // instead of `application/json` with the model in a param named `model`.
1120
+ // Useful when interfacing with server-side languages like **PHP** that make
1121
+ // it difficult to read the body of `PUT` requests.
1122
+ Backbone.sync = function(method, model, options) {
1123
+ var type = methodMap[method];
1124
+
1125
+ // Default options, unless specified.
1126
+ _.defaults(options || (options = {}), {
1127
+ emulateHTTP: Backbone.emulateHTTP,
1128
+ emulateJSON: Backbone.emulateJSON
1129
+ });
1130
+
1131
+ // Default JSON-request options.
1132
+ var params = {type: type, dataType: 'json'};
1133
+
1134
+ // Ensure that we have a URL.
1135
+ if (!options.url) {
1136
+ params.url = _.result(model, 'url') || urlError();
1137
+ }
1138
+
1139
+ // Ensure that we have the appropriate request data.
1140
+ if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
1141
+ params.contentType = 'application/json';
1142
+ params.data = JSON.stringify(options.attrs || model.toJSON(options));
1143
+ }
1144
+
1145
+ // For older servers, emulate JSON by encoding the request into an HTML-form.
1146
+ if (options.emulateJSON) {
1147
+ params.contentType = 'application/x-www-form-urlencoded';
1148
+ params.data = params.data ? {model: params.data} : {};
1149
+ }
1150
+
1151
+ // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
1152
+ // And an `X-HTTP-Method-Override` header.
1153
+ if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
1154
+ params.type = 'POST';
1155
+ if (options.emulateJSON) params.data._method = type;
1156
+ var beforeSend = options.beforeSend;
1157
+ options.beforeSend = function(xhr) {
1158
+ xhr.setRequestHeader('X-HTTP-Method-Override', type);
1159
+ if (beforeSend) return beforeSend.apply(this, arguments);
1160
+ };
1161
+ }
1162
+
1163
+ // Don't process data on a non-GET request.
1164
+ if (params.type !== 'GET' && !options.emulateJSON) {
1165
+ params.processData = false;
1166
+ }
1167
+
1168
+ // If we're sending a `PATCH` request, and we're in an old Internet Explorer
1169
+ // that still has ActiveX enabled by default, override jQuery to use that
1170
+ // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8.
1171
+ if (params.type === 'PATCH' && noXhrPatch) {
1172
+ params.xhr = function() {
1173
+ return new ActiveXObject("Microsoft.XMLHTTP");
1174
+ };
1175
+ }
1176
+
1177
+ // Make the request, allowing the user to override any Ajax options.
1178
+ var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
1179
+ model.trigger('request', model, xhr, options);
1180
+ return xhr;
1181
+ };
1182
+
1183
+ var noXhrPatch = typeof window !== 'undefined' && !!window.ActiveXObject && !(window.XMLHttpRequest && (new XMLHttpRequest).dispatchEvent);
1184
+
1185
+ // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
1186
+ var methodMap = {
1187
+ 'create': 'POST',
1188
+ 'update': 'PUT',
1189
+ 'patch': 'PATCH',
1190
+ 'delete': 'DELETE',
1191
+ 'read': 'GET'
1192
+ };
1193
+
1194
+ // Set the default implementation of `Backbone.ajax` to proxy through to `$`.
1195
+ // Override this if you'd like to use a different library.
1196
+ Backbone.ajax = function() {
1197
+ return Backbone.$.ajax.apply(Backbone.$, arguments);
1198
+ };
1199
+
1200
+ // Backbone.Router
1201
+ // ---------------
1202
+
1203
+ // Routers map faux-URLs to actions, and fire events when routes are
1204
+ // matched. Creating a new one sets its `routes` hash, if not set statically.
1205
+ var Router = Backbone.Router = function(options) {
1206
+ options || (options = {});
1207
+ if (options.routes) this.routes = options.routes;
1208
+ this._bindRoutes();
1209
+ this.initialize.apply(this, arguments);
1210
+ };
1211
+
1212
+ // Cached regular expressions for matching named param parts and splatted
1213
+ // parts of route strings.
1214
+ var optionalParam = /\((.*?)\)/g;
1215
+ var namedParam = /(\(\?)?:\w+/g;
1216
+ var splatParam = /\*\w+/g;
1217
+ var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
1218
+
1219
+ // Set up all inheritable **Backbone.Router** properties and methods.
1220
+ _.extend(Router.prototype, Events, {
1221
+
1222
+ // Initialize is an empty function by default. Override it with your own
1223
+ // initialization logic.
1224
+ initialize: function(){},
1225
+
1226
+ // Manually bind a single named route to a callback. For example:
1227
+ //
1228
+ // this.route('search/:query/p:num', 'search', function(query, num) {
1229
+ // ...
1230
+ // });
1231
+ //
1232
+ route: function(route, name, callback) {
1233
+ if (!_.isRegExp(route)) route = this._routeToRegExp(route);
1234
+ if (_.isFunction(name)) {
1235
+ callback = name;
1236
+ name = '';
1237
+ }
1238
+ if (!callback) callback = this[name];
1239
+ var router = this;
1240
+ Backbone.history.route(route, function(fragment) {
1241
+ var args = router._extractParameters(route, fragment);
1242
+ callback && callback.apply(router, args);
1243
+ router.trigger.apply(router, ['route:' + name].concat(args));
1244
+ router.trigger('route', name, args);
1245
+ Backbone.history.trigger('route', router, name, args);
1246
+ });
1247
+ return this;
1248
+ },
1249
+
1250
+ // Simple proxy to `Backbone.history` to save a fragment into the history.
1251
+ navigate: function(fragment, options) {
1252
+ Backbone.history.navigate(fragment, options);
1253
+ return this;
1254
+ },
1255
+
1256
+ // Bind all defined routes to `Backbone.history`. We have to reverse the
1257
+ // order of the routes here to support behavior where the most general
1258
+ // routes can be defined at the bottom of the route map.
1259
+ _bindRoutes: function() {
1260
+ if (!this.routes) return;
1261
+ this.routes = _.result(this, 'routes');
1262
+ var route, routes = _.keys(this.routes);
1263
+ while ((route = routes.pop()) != null) {
1264
+ this.route(route, this.routes[route]);
1265
+ }
1266
+ },
1267
+
1268
+ // Convert a route string into a regular expression, suitable for matching
1269
+ // against the current location hash.
1270
+ _routeToRegExp: function(route) {
1271
+ route = route.replace(escapeRegExp, '\\$&')
1272
+ .replace(optionalParam, '(?:$1)?')
1273
+ .replace(namedParam, function(match, optional) {
1274
+ return optional ? match : '([^\/]+)';
1275
+ })
1276
+ .replace(splatParam, '(.*?)');
1277
+ return new RegExp('^' + route + '$');
1278
+ },
1279
+
1280
+ // Given a route, and a URL fragment that it matches, return the array of
1281
+ // extracted decoded parameters. Empty or unmatched parameters will be
1282
+ // treated as `null` to normalize cross-browser behavior.
1283
+ _extractParameters: function(route, fragment) {
1284
+ var params = route.exec(fragment).slice(1);
1285
+ return _.map(params, function(param) {
1286
+ return param ? decodeURIComponent(param) : null;
1287
+ });
1288
+ }
1289
+
1290
+ });
1291
+
1292
+ // Backbone.History
1293
+ // ----------------
1294
+
1295
+ // Handles cross-browser history management, based on either
1296
+ // [pushState](http://diveintohtml5.info/history.html) and real URLs, or
1297
+ // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
1298
+ // and URL fragments. If the browser supports neither (old IE, natch),
1299
+ // falls back to polling.
1300
+ var History = Backbone.History = function() {
1301
+ this.handlers = [];
1302
+ _.bindAll(this, 'checkUrl');
1303
+
1304
+ // Ensure that `History` can be used outside of the browser.
1305
+ if (typeof window !== 'undefined') {
1306
+ this.location = window.location;
1307
+ this.history = window.history;
1308
+ }
1309
+ };
1310
+
1311
+ // Cached regex for stripping a leading hash/slash and trailing space.
1312
+ var routeStripper = /^[#\/]|\s+$/g;
1313
+
1314
+ // Cached regex for stripping leading and trailing slashes.
1315
+ var rootStripper = /^\/+|\/+$/g;
1316
+
1317
+ // Cached regex for detecting MSIE.
1318
+ var isExplorer = /msie [\w.]+/;
1319
+
1320
+ // Cached regex for removing a trailing slash.
1321
+ var trailingSlash = /\/$/;
1322
+
1323
+ // Cached regex for stripping urls of hash and query.
1324
+ var pathStripper = /[?#].*$/;
1325
+
1326
+ // Has the history handling already been started?
1327
+ History.started = false;
1328
+
1329
+ // Set up all inheritable **Backbone.History** properties and methods.
1330
+ _.extend(History.prototype, Events, {
1331
+
1332
+ // The default interval to poll for hash changes, if necessary, is
1333
+ // twenty times a second.
1334
+ interval: 50,
1335
+
1336
+ // Gets the true hash value. Cannot use location.hash directly due to bug
1337
+ // in Firefox where location.hash will always be decoded.
1338
+ getHash: function(window) {
1339
+ var match = (window || this).location.href.match(/#(.*)$/);
1340
+ return match ? match[1] : '';
1341
+ },
1342
+
1343
+ // Get the cross-browser normalized URL fragment, either from the URL,
1344
+ // the hash, or the override.
1345
+ getFragment: function(fragment, forcePushState) {
1346
+ if (fragment == null) {
1347
+ if (this._hasPushState || !this._wantsHashChange || forcePushState) {
1348
+ fragment = this.location.pathname;
1349
+ var root = this.root.replace(trailingSlash, '');
1350
+ if (!fragment.indexOf(root)) fragment = fragment.slice(root.length);
1351
+ } else {
1352
+ fragment = this.getHash();
1353
+ }
1354
+ }
1355
+ return fragment.replace(routeStripper, '');
1356
+ },
1357
+
1358
+ // Start the hash change handling, returning `true` if the current URL matches
1359
+ // an existing route, and `false` otherwise.
1360
+ start: function(options) {
1361
+ if (History.started) throw new Error("Backbone.history has already been started");
1362
+ History.started = true;
1363
+
1364
+ // Figure out the initial configuration. Do we need an iframe?
1365
+ // Is pushState desired ... is it available?
1366
+ this.options = _.extend({root: '/'}, this.options, options);
1367
+ this.root = this.options.root;
1368
+ this._wantsHashChange = this.options.hashChange !== false;
1369
+ this._wantsPushState = !!this.options.pushState;
1370
+ this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
1371
+ var fragment = this.getFragment();
1372
+ var docMode = document.documentMode;
1373
+ var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
1374
+
1375
+ // Normalize root to always include a leading and trailing slash.
1376
+ this.root = ('/' + this.root + '/').replace(rootStripper, '/');
1377
+
1378
+ if (oldIE && this._wantsHashChange) {
1379
+ this.iframe = Backbone.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
1380
+ this.navigate(fragment);
1381
+ }
1382
+
1383
+ // Depending on whether we're using pushState or hashes, and whether
1384
+ // 'onhashchange' is supported, determine how we check the URL state.
1385
+ if (this._hasPushState) {
1386
+ Backbone.$(window).on('popstate', this.checkUrl);
1387
+ } else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
1388
+ Backbone.$(window).on('hashchange', this.checkUrl);
1389
+ } else if (this._wantsHashChange) {
1390
+ this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
1391
+ }
1392
+
1393
+ // Determine if we need to change the base url, for a pushState link
1394
+ // opened by a non-pushState browser.
1395
+ this.fragment = fragment;
1396
+ var loc = this.location;
1397
+ var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;
1398
+
1399
+ // Transition from hashChange to pushState or vice versa if both are
1400
+ // requested.
1401
+ if (this._wantsHashChange && this._wantsPushState) {
1402
+
1403
+ // If we've started off with a route from a `pushState`-enabled
1404
+ // browser, but we're currently in a browser that doesn't support it...
1405
+ if (!this._hasPushState && !atRoot) {
1406
+ this.fragment = this.getFragment(null, true);
1407
+ this.location.replace(this.root + this.location.search + '#' + this.fragment);
1408
+ // Return immediately as browser will do redirect to new url
1409
+ return true;
1410
+
1411
+ // Or if we've started out with a hash-based route, but we're currently
1412
+ // in a browser where it could be `pushState`-based instead...
1413
+ } else if (this._hasPushState && atRoot && loc.hash) {
1414
+ this.fragment = this.getHash().replace(routeStripper, '');
1415
+ this.history.replaceState({}, document.title, this.root + this.fragment + loc.search);
1416
+ }
1417
+
1418
+ }
1419
+
1420
+ if (!this.options.silent) return this.loadUrl();
1421
+ },
1422
+
1423
+ // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
1424
+ // but possibly useful for unit testing Routers.
1425
+ stop: function() {
1426
+ Backbone.$(window).off('popstate', this.checkUrl).off('hashchange', this.checkUrl);
1427
+ clearInterval(this._checkUrlInterval);
1428
+ History.started = false;
1429
+ },
1430
+
1431
+ // Add a route to be tested when the fragment changes. Routes added later
1432
+ // may override previous routes.
1433
+ route: function(route, callback) {
1434
+ this.handlers.unshift({route: route, callback: callback});
1435
+ },
1436
+
1437
+ // Checks the current URL to see if it has changed, and if it has,
1438
+ // calls `loadUrl`, normalizing across the hidden iframe.
1439
+ checkUrl: function(e) {
1440
+ var current = this.getFragment();
1441
+ if (current === this.fragment && this.iframe) {
1442
+ current = this.getFragment(this.getHash(this.iframe));
1443
+ }
1444
+ if (current === this.fragment) return false;
1445
+ if (this.iframe) this.navigate(current);
1446
+ this.loadUrl();
1447
+ },
1448
+
1449
+ // Attempt to load the current URL fragment. If a route succeeds with a
1450
+ // match, returns `true`. If no defined routes matches the fragment,
1451
+ // returns `false`.
1452
+ loadUrl: function(fragment) {
1453
+ fragment = this.fragment = this.getFragment(fragment);
1454
+ return _.any(this.handlers, function(handler) {
1455
+ if (handler.route.test(fragment)) {
1456
+ handler.callback(fragment);
1457
+ return true;
1458
+ }
1459
+ });
1460
+ },
1461
+
1462
+ // Save a fragment into the hash history, or replace the URL state if the
1463
+ // 'replace' option is passed. You are responsible for properly URL-encoding
1464
+ // the fragment in advance.
1465
+ //
1466
+ // The options object can contain `trigger: true` if you wish to have the
1467
+ // route callback be fired (not usually desirable), or `replace: true`, if
1468
+ // you wish to modify the current URL without adding an entry to the history.
1469
+ navigate: function(fragment, options) {
1470
+ if (!History.started) return false;
1471
+ if (!options || options === true) options = {trigger: !!options};
1472
+
1473
+ var url = this.root + (fragment = this.getFragment(fragment || ''));
1474
+
1475
+ // Strip the fragment of the query and hash for matching.
1476
+ fragment = fragment.replace(pathStripper, '');
1477
+
1478
+ if (this.fragment === fragment) return;
1479
+ this.fragment = fragment;
1480
+
1481
+ // Don't include a trailing slash on the root.
1482
+ if (fragment === '' && url !== '/') url = url.slice(0, -1);
1483
+
1484
+ // If pushState is available, we use it to set the fragment as a real URL.
1485
+ if (this._hasPushState) {
1486
+ this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
1487
+
1488
+ // If hash changes haven't been explicitly disabled, update the hash
1489
+ // fragment to store history.
1490
+ } else if (this._wantsHashChange) {
1491
+ this._updateHash(this.location, fragment, options.replace);
1492
+ if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) {
1493
+ // Opening and closing the iframe tricks IE7 and earlier to push a
1494
+ // history entry on hash-tag change. When replace is true, we don't
1495
+ // want this.
1496
+ if(!options.replace) this.iframe.document.open().close();
1497
+ this._updateHash(this.iframe.location, fragment, options.replace);
1498
+ }
1499
+
1500
+ // If you've told us that you explicitly don't want fallback hashchange-
1501
+ // based history, then `navigate` becomes a page refresh.
1502
+ } else {
1503
+ return this.location.assign(url);
1504
+ }
1505
+ if (options.trigger) return this.loadUrl(fragment);
1506
+ },
1507
+
1508
+ // Update the hash location, either replacing the current entry, or adding
1509
+ // a new one to the browser history.
1510
+ _updateHash: function(location, fragment, replace) {
1511
+ if (replace) {
1512
+ var href = location.href.replace(/(javascript:|#).*$/, '');
1513
+ location.replace(href + '#' + fragment);
1514
+ } else {
1515
+ // Some browsers require that `hash` contains a leading #.
1516
+ location.hash = '#' + fragment;
1517
+ }
1518
+ }
1519
+
1520
+ });
1521
+
1522
+ // Create the default Backbone.history.
1523
+ Backbone.history = new History;
1524
+
1525
+ // Helpers
1526
+ // -------
1527
+
1528
+ // Helper function to correctly set up the prototype chain, for subclasses.
1529
+ // Similar to `goog.inherits`, but uses a hash of prototype properties and
1530
+ // class properties to be extended.
1531
+ var extend = function(protoProps, staticProps) {
1532
+ var parent = this;
1533
+ var child;
1534
+
1535
+ // The constructor function for the new subclass is either defined by you
1536
+ // (the "constructor" property in your `extend` definition), or defaulted
1537
+ // by us to simply call the parent's constructor.
1538
+ if (protoProps && _.has(protoProps, 'constructor')) {
1539
+ child = protoProps.constructor;
1540
+ } else {
1541
+ child = function(){ return parent.apply(this, arguments); };
1542
+ }
1543
+
1544
+ // Add static properties to the constructor function, if supplied.
1545
+ _.extend(child, parent, staticProps);
1546
+
1547
+ // Set the prototype chain to inherit from `parent`, without calling
1548
+ // `parent`'s constructor function.
1549
+ var Surrogate = function(){ this.constructor = child; };
1550
+ Surrogate.prototype = parent.prototype;
1551
+ child.prototype = new Surrogate;
1552
+
1553
+ // Add prototype properties (instance properties) to the subclass,
1554
+ // if supplied.
1555
+ if (protoProps) _.extend(child.prototype, protoProps);
1556
+
1557
+ // Set a convenience property in case the parent's prototype is needed
1558
+ // later.
1559
+ child.__super__ = parent.prototype;
1560
+
1561
+ return child;
1562
+ };
1563
+
1564
+ // Set up inheritance for the model, collection, router, view and history.
1565
+ Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
1566
+
1567
+ // Throw an error when a URL is needed, and none is supplied.
1568
+ var urlError = function() {
1569
+ throw new Error('A "url" property or function must be specified');
1570
+ };
1571
+
1572
+ // Wrap an optional error callback with a fallback error event.
1573
+ var wrapError = function(model, options) {
1574
+ var error = options.error;
1575
+ options.error = function(resp) {
1576
+ if (error) error(model, resp, options);
1577
+ model.trigger('error', model, resp, options);
1578
+ };
1579
+ };
1580
+
1581
+ }).call(this);
1582
+
1583
+ // MarionetteJS (Backbone.Marionette)
1584
+ // ----------------------------------
1585
+ // v1.4.1
1586
+ //
1587
+ // Copyright (c)2013 Derick Bailey, Muted Solutions, LLC.
1588
+ // Distributed under MIT license
1589
+ //
1590
+ // http://marionettejs.com
1591
+
1592
+
1593
+
1594
+ /*!
1595
+ * Includes BabySitter
1596
+ * https://github.com/marionettejs/backbone.babysitter/
1597
+ *
1598
+ * Includes Wreqr
1599
+ * https://github.com/marionettejs/backbone.wreqr/
1600
+ */
1601
+
1602
+ // Backbone.BabySitter
1603
+ // -------------------
1604
+ // v0.0.6
1605
+ //
1606
+ // Copyright (c)2013 Derick Bailey, Muted Solutions, LLC.
1607
+ // Distributed under MIT license
1608
+ //
1609
+ // http://github.com/babysitterjs/backbone.babysitter
1610
+
1611
+ // Backbone.ChildViewContainer
1612
+ // ---------------------------
1613
+ //
1614
+ // Provide a container to store, retrieve and
1615
+ // shut down child views.
1616
+
1617
+ Backbone.ChildViewContainer = (function(Backbone, _){
1618
+
1619
+ // Container Constructor
1620
+ // ---------------------
1621
+
1622
+ var Container = function(views){
1623
+ this._views = {};
1624
+ this._indexByModel = {};
1625
+ this._indexByCustom = {};
1626
+ this._updateLength();
1627
+
1628
+ _.each(views, this.add, this);
1629
+ };
1630
+
1631
+ // Container Methods
1632
+ // -----------------
1633
+
1634
+ _.extend(Container.prototype, {
1635
+
1636
+ // Add a view to this container. Stores the view
1637
+ // by `cid` and makes it searchable by the model
1638
+ // cid (and model itself). Optionally specify
1639
+ // a custom key to store an retrieve the view.
1640
+ add: function(view, customIndex){
1641
+ var viewCid = view.cid;
1642
+
1643
+ // store the view
1644
+ this._views[viewCid] = view;
1645
+
1646
+ // index it by model
1647
+ if (view.model){
1648
+ this._indexByModel[view.model.cid] = viewCid;
1649
+ }
1650
+
1651
+ // index by custom
1652
+ if (customIndex){
1653
+ this._indexByCustom[customIndex] = viewCid;
1654
+ }
1655
+
1656
+ this._updateLength();
1657
+ },
1658
+
1659
+ // Find a view by the model that was attached to
1660
+ // it. Uses the model's `cid` to find it.
1661
+ findByModel: function(model){
1662
+ return this.findByModelCid(model.cid);
1663
+ },
1664
+
1665
+ // Find a view by the `cid` of the model that was attached to
1666
+ // it. Uses the model's `cid` to find the view `cid` and
1667
+ // retrieve the view using it.
1668
+ findByModelCid: function(modelCid){
1669
+ var viewCid = this._indexByModel[modelCid];
1670
+ return this.findByCid(viewCid);
1671
+ },
1672
+
1673
+ // Find a view by a custom indexer.
1674
+ findByCustom: function(index){
1675
+ var viewCid = this._indexByCustom[index];
1676
+ return this.findByCid(viewCid);
1677
+ },
1678
+
1679
+ // Find by index. This is not guaranteed to be a
1680
+ // stable index.
1681
+ findByIndex: function(index){
1682
+ return _.values(this._views)[index];
1683
+ },
1684
+
1685
+ // retrieve a view by it's `cid` directly
1686
+ findByCid: function(cid){
1687
+ return this._views[cid];
1688
+ },
1689
+
1690
+ // Remove a view
1691
+ remove: function(view){
1692
+ var viewCid = view.cid;
1693
+
1694
+ // delete model index
1695
+ if (view.model){
1696
+ delete this._indexByModel[view.model.cid];
1697
+ }
1698
+
1699
+ // delete custom index
1700
+ _.any(this._indexByCustom, function(cid, key) {
1701
+ if (cid === viewCid) {
1702
+ delete this._indexByCustom[key];
1703
+ return true;
1704
+ }
1705
+ }, this);
1706
+
1707
+ // remove the view from the container
1708
+ delete this._views[viewCid];
1709
+
1710
+ // update the length
1711
+ this._updateLength();
1712
+ },
1713
+
1714
+ // Call a method on every view in the container,
1715
+ // passing parameters to the call method one at a
1716
+ // time, like `function.call`.
1717
+ call: function(method){
1718
+ this.apply(method, _.tail(arguments));
1719
+ },
1720
+
1721
+ // Apply a method on every view in the container,
1722
+ // passing parameters to the call method one at a
1723
+ // time, like `function.apply`.
1724
+ apply: function(method, args){
1725
+ _.each(this._views, function(view){
1726
+ if (_.isFunction(view[method])){
1727
+ view[method].apply(view, args || []);
1728
+ }
1729
+ });
1730
+ },
1731
+
1732
+ // Update the `.length` attribute on this container
1733
+ _updateLength: function(){
1734
+ this.length = _.size(this._views);
1735
+ }
1736
+ });
1737
+
1738
+ // Borrowing this code from Backbone.Collection:
1739
+ // http://backbonejs.org/docs/backbone.html#section-106
1740
+ //
1741
+ // Mix in methods from Underscore, for iteration, and other
1742
+ // collection related features.
1743
+ var methods = ['forEach', 'each', 'map', 'find', 'detect', 'filter',
1744
+ 'select', 'reject', 'every', 'all', 'some', 'any', 'include',
1745
+ 'contains', 'invoke', 'toArray', 'first', 'initial', 'rest',
1746
+ 'last', 'without', 'isEmpty', 'pluck'];
1747
+
1748
+ _.each(methods, function(method) {
1749
+ Container.prototype[method] = function() {
1750
+ var views = _.values(this._views);
1751
+ var args = [views].concat(_.toArray(arguments));
1752
+ return _[method].apply(_, args);
1753
+ };
1754
+ });
1755
+
1756
+ // return the public API
1757
+ return Container;
1758
+ })(Backbone, _);
1759
+
1760
+ // Backbone.Wreqr (Backbone.Marionette)
1761
+ // ----------------------------------
1762
+ // v0.2.0
1763
+ //
1764
+ // Copyright (c)2013 Derick Bailey, Muted Solutions, LLC.
1765
+ // Distributed under MIT license
1766
+ //
1767
+ // http://github.com/marionettejs/backbone.wreqr
1768
+
1769
+
1770
+ Backbone.Wreqr = (function(Backbone, Marionette, _){
1771
+ "use strict";
1772
+ var Wreqr = {};
1773
+
1774
+ // Handlers
1775
+ // --------
1776
+ // A registry of functions to call, given a name
1777
+
1778
+ Wreqr.Handlers = (function(Backbone, _){
1779
+ "use strict";
1780
+
1781
+ // Constructor
1782
+ // -----------
1783
+
1784
+ var Handlers = function(options){
1785
+ this.options = options;
1786
+ this._wreqrHandlers = {};
1787
+
1788
+ if (_.isFunction(this.initialize)){
1789
+ this.initialize(options);
1790
+ }
1791
+ };
1792
+
1793
+ Handlers.extend = Backbone.Model.extend;
1794
+
1795
+ // Instance Members
1796
+ // ----------------
1797
+
1798
+ _.extend(Handlers.prototype, Backbone.Events, {
1799
+
1800
+ // Add multiple handlers using an object literal configuration
1801
+ setHandlers: function(handlers){
1802
+ _.each(handlers, function(handler, name){
1803
+ var context = null;
1804
+
1805
+ if (_.isObject(handler) && !_.isFunction(handler)){
1806
+ context = handler.context;
1807
+ handler = handler.callback;
1808
+ }
1809
+
1810
+ this.setHandler(name, handler, context);
1811
+ }, this);
1812
+ },
1813
+
1814
+ // Add a handler for the given name, with an
1815
+ // optional context to run the handler within
1816
+ setHandler: function(name, handler, context){
1817
+ var config = {
1818
+ callback: handler,
1819
+ context: context
1820
+ };
1821
+
1822
+ this._wreqrHandlers[name] = config;
1823
+
1824
+ this.trigger("handler:add", name, handler, context);
1825
+ },
1826
+
1827
+ // Determine whether or not a handler is registered
1828
+ hasHandler: function(name){
1829
+ return !! this._wreqrHandlers[name];
1830
+ },
1831
+
1832
+ // Get the currently registered handler for
1833
+ // the specified name. Throws an exception if
1834
+ // no handler is found.
1835
+ getHandler: function(name){
1836
+ var config = this._wreqrHandlers[name];
1837
+
1838
+ if (!config){
1839
+ throw new Error("Handler not found for '" + name + "'");
1840
+ }
1841
+
1842
+ return function(){
1843
+ var args = Array.prototype.slice.apply(arguments);
1844
+ return config.callback.apply(config.context, args);
1845
+ };
1846
+ },
1847
+
1848
+ // Remove a handler for the specified name
1849
+ removeHandler: function(name){
1850
+ delete this._wreqrHandlers[name];
1851
+ },
1852
+
1853
+ // Remove all handlers from this registry
1854
+ removeAllHandlers: function(){
1855
+ this._wreqrHandlers = {};
1856
+ }
1857
+ });
1858
+
1859
+ return Handlers;
1860
+ })(Backbone, _);
1861
+
1862
+ // Wreqr.CommandStorage
1863
+ // --------------------
1864
+ //
1865
+ // Store and retrieve commands for execution.
1866
+ Wreqr.CommandStorage = (function(){
1867
+ "use strict";
1868
+
1869
+ // Constructor function
1870
+ var CommandStorage = function(options){
1871
+ this.options = options;
1872
+ this._commands = {};
1873
+
1874
+ if (_.isFunction(this.initialize)){
1875
+ this.initialize(options);
1876
+ }
1877
+ };
1878
+
1879
+ // Instance methods
1880
+ _.extend(CommandStorage.prototype, Backbone.Events, {
1881
+
1882
+ // Get an object literal by command name, that contains
1883
+ // the `commandName` and the `instances` of all commands
1884
+ // represented as an array of arguments to process
1885
+ getCommands: function(commandName){
1886
+ var commands = this._commands[commandName];
1887
+
1888
+ // we don't have it, so add it
1889
+ if (!commands){
1890
+
1891
+ // build the configuration
1892
+ commands = {
1893
+ command: commandName,
1894
+ instances: []
1895
+ };
1896
+
1897
+ // store it
1898
+ this._commands[commandName] = commands;
1899
+ }
1900
+
1901
+ return commands;
1902
+ },
1903
+
1904
+ // Add a command by name, to the storage and store the
1905
+ // args for the command
1906
+ addCommand: function(commandName, args){
1907
+ var command = this.getCommands(commandName);
1908
+ command.instances.push(args);
1909
+ },
1910
+
1911
+ // Clear all commands for the given `commandName`
1912
+ clearCommands: function(commandName){
1913
+ var command = this.getCommands(commandName);
1914
+ command.instances = [];
1915
+ }
1916
+ });
1917
+
1918
+ return CommandStorage;
1919
+ })();
1920
+
1921
+ // Wreqr.Commands
1922
+ // --------------
1923
+ //
1924
+ // A simple command pattern implementation. Register a command
1925
+ // handler and execute it.
1926
+ Wreqr.Commands = (function(Wreqr){
1927
+ "use strict";
1928
+
1929
+ return Wreqr.Handlers.extend({
1930
+ // default storage type
1931
+ storageType: Wreqr.CommandStorage,
1932
+
1933
+ constructor: function(options){
1934
+ this.options = options || {};
1935
+
1936
+ this._initializeStorage(this.options);
1937
+ this.on("handler:add", this._executeCommands, this);
1938
+
1939
+ var args = Array.prototype.slice.call(arguments);
1940
+ Wreqr.Handlers.prototype.constructor.apply(this, args);
1941
+ },
1942
+
1943
+ // Execute a named command with the supplied args
1944
+ execute: function(name, args){
1945
+ name = arguments[0];
1946
+ args = Array.prototype.slice.call(arguments, 1);
1947
+
1948
+ if (this.hasHandler(name)){
1949
+ this.getHandler(name).apply(this, args);
1950
+ } else {
1951
+ this.storage.addCommand(name, args);
1952
+ }
1953
+
1954
+ },
1955
+
1956
+ // Internal method to handle bulk execution of stored commands
1957
+ _executeCommands: function(name, handler, context){
1958
+ var command = this.storage.getCommands(name);
1959
+
1960
+ // loop through and execute all the stored command instances
1961
+ _.each(command.instances, function(args){
1962
+ handler.apply(context, args);
1963
+ });
1964
+
1965
+ this.storage.clearCommands(name);
1966
+ },
1967
+
1968
+ // Internal method to initialize storage either from the type's
1969
+ // `storageType` or the instance `options.storageType`.
1970
+ _initializeStorage: function(options){
1971
+ var storage;
1972
+
1973
+ var StorageType = options.storageType || this.storageType;
1974
+ if (_.isFunction(StorageType)){
1975
+ storage = new StorageType();
1976
+ } else {
1977
+ storage = StorageType;
1978
+ }
1979
+
1980
+ this.storage = storage;
1981
+ }
1982
+ });
1983
+
1984
+ })(Wreqr);
1985
+
1986
+ // Wreqr.RequestResponse
1987
+ // ---------------------
1988
+ //
1989
+ // A simple request/response implementation. Register a
1990
+ // request handler, and return a response from it
1991
+ Wreqr.RequestResponse = (function(Wreqr){
1992
+ "use strict";
1993
+
1994
+ return Wreqr.Handlers.extend({
1995
+ request: function(){
1996
+ var name = arguments[0];
1997
+ var args = Array.prototype.slice.call(arguments, 1);
1998
+
1999
+ return this.getHandler(name).apply(this, args);
2000
+ }
2001
+ });
2002
+
2003
+ })(Wreqr);
2004
+
2005
+ // Event Aggregator
2006
+ // ----------------
2007
+ // A pub-sub object that can be used to decouple various parts
2008
+ // of an application through event-driven architecture.
2009
+
2010
+ Wreqr.EventAggregator = (function(Backbone, _){
2011
+ "use strict";
2012
+ var EA = function(){};
2013
+
2014
+ // Copy the `extend` function used by Backbone's classes
2015
+ EA.extend = Backbone.Model.extend;
2016
+
2017
+ // Copy the basic Backbone.Events on to the event aggregator
2018
+ _.extend(EA.prototype, Backbone.Events);
2019
+
2020
+ return EA;
2021
+ })(Backbone, _);
2022
+
2023
+
2024
+ return Wreqr;
2025
+ })(Backbone, Backbone.Marionette, _);
2026
+
2027
+ var Marionette = (function(global, Backbone, _){
2028
+ "use strict";
2029
+
2030
+ // Define and export the Marionette namespace
2031
+ var Marionette = {};
2032
+ Backbone.Marionette = Marionette;
2033
+
2034
+ // Get the DOM manipulator for later use
2035
+ Marionette.$ = Backbone.$;
2036
+
2037
+ // Helpers
2038
+ // -------
2039
+
2040
+ // For slicing `arguments` in functions
2041
+ var protoSlice = Array.prototype.slice;
2042
+ function slice(args) {
2043
+ return protoSlice.call(args);
2044
+ }
2045
+
2046
+ function throwError(message, name) {
2047
+ var error = new Error(message);
2048
+ error.name = name || 'Error';
2049
+ throw error;
2050
+ }
2051
+
2052
+ // Marionette.extend
2053
+ // -----------------
2054
+
2055
+ // Borrow the Backbone `extend` method so we can use it as needed
2056
+ Marionette.extend = Backbone.Model.extend;
2057
+
2058
+ // Marionette.getOption
2059
+ // --------------------
2060
+
2061
+ // Retrieve an object, function or other value from a target
2062
+ // object or its `options`, with `options` taking precedence.
2063
+ Marionette.getOption = function(target, optionName){
2064
+ if (!target || !optionName){ return; }
2065
+ var value;
2066
+
2067
+ if (target.options && (optionName in target.options) && (target.options[optionName] !== undefined)){
2068
+ value = target.options[optionName];
2069
+ } else {
2070
+ value = target[optionName];
2071
+ }
2072
+
2073
+ return value;
2074
+ };
2075
+
2076
+ // Trigger an event and/or a corresponding method name. Examples:
2077
+ //
2078
+ // `this.triggerMethod("foo")` will trigger the "foo" event and
2079
+ // call the "onFoo" method.
2080
+ //
2081
+ // `this.triggerMethod("foo:bar") will trigger the "foo:bar" event and
2082
+ // call the "onFooBar" method.
2083
+ Marionette.triggerMethod = (function(){
2084
+
2085
+ // split the event name on the :
2086
+ var splitter = /(^|:)(\w)/gi;
2087
+
2088
+ // take the event section ("section1:section2:section3")
2089
+ // and turn it in to uppercase name
2090
+ function getEventName(match, prefix, eventName) {
2091
+ return eventName.toUpperCase();
2092
+ }
2093
+
2094
+ // actual triggerMethod name
2095
+ var triggerMethod = function(event) {
2096
+ // get the method name from the event name
2097
+ var methodName = 'on' + event.replace(splitter, getEventName);
2098
+ var method = this[methodName];
2099
+
2100
+ // trigger the event, if a trigger method exists
2101
+ if(_.isFunction(this.trigger)) {
2102
+ this.trigger.apply(this, arguments);
2103
+ }
2104
+
2105
+ // call the onMethodName if it exists
2106
+ if (_.isFunction(method)) {
2107
+ // pass all arguments, except the event name
2108
+ return method.apply(this, _.tail(arguments));
2109
+ }
2110
+ };
2111
+
2112
+ return triggerMethod;
2113
+ })();
2114
+
2115
+ // DOMRefresh
2116
+ // ----------
2117
+ //
2118
+ // Monitor a view's state, and after it has been rendered and shown
2119
+ // in the DOM, trigger a "dom:refresh" event every time it is
2120
+ // re-rendered.
2121
+
2122
+ Marionette.MonitorDOMRefresh = (function(){
2123
+ // track when the view has been shown in the DOM,
2124
+ // using a Marionette.Region (or by other means of triggering "show")
2125
+ function handleShow(view){
2126
+ view._isShown = true;
2127
+ triggerDOMRefresh(view);
2128
+ }
2129
+
2130
+ // track when the view has been rendered
2131
+ function handleRender(view){
2132
+ view._isRendered = true;
2133
+ triggerDOMRefresh(view);
2134
+ }
2135
+
2136
+ // Trigger the "dom:refresh" event and corresponding "onDomRefresh" method
2137
+ function triggerDOMRefresh(view){
2138
+ if (view._isShown && view._isRendered){
2139
+ if (_.isFunction(view.triggerMethod)){
2140
+ view.triggerMethod("dom:refresh");
2141
+ }
2142
+ }
2143
+ }
2144
+
2145
+ // Export public API
2146
+ return function(view){
2147
+ view.listenTo(view, "show", function(){
2148
+ handleShow(view);
2149
+ });
2150
+
2151
+ view.listenTo(view, "render", function(){
2152
+ handleRender(view);
2153
+ });
2154
+ };
2155
+ })();
2156
+
2157
+
2158
+ // Marionette.bindEntityEvents & unbindEntityEvents
2159
+ // ---------------------------
2160
+ //
2161
+ // These methods are used to bind/unbind a backbone "entity" (collection/model)
2162
+ // to methods on a target object.
2163
+ //
2164
+ // The first parameter, `target`, must have a `listenTo` method from the
2165
+ // EventBinder object.
2166
+ //
2167
+ // The second parameter is the entity (Backbone.Model or Backbone.Collection)
2168
+ // to bind the events from.
2169
+ //
2170
+ // The third parameter is a hash of { "event:name": "eventHandler" }
2171
+ // configuration. Multiple handlers can be separated by a space. A
2172
+ // function can be supplied instead of a string handler name.
2173
+
2174
+ (function(Marionette){
2175
+ "use strict";
2176
+
2177
+ // Bind the event to handlers specified as a string of
2178
+ // handler names on the target object
2179
+ function bindFromStrings(target, entity, evt, methods){
2180
+ var methodNames = methods.split(/\s+/);
2181
+
2182
+ _.each(methodNames,function(methodName) {
2183
+
2184
+ var method = target[methodName];
2185
+ if(!method) {
2186
+ throwError("Method '"+ methodName +"' was configured as an event handler, but does not exist.");
2187
+ }
2188
+
2189
+ target.listenTo(entity, evt, method, target);
2190
+ });
2191
+ }
2192
+
2193
+ // Bind the event to a supplied callback function
2194
+ function bindToFunction(target, entity, evt, method){
2195
+ target.listenTo(entity, evt, method, target);
2196
+ }
2197
+
2198
+ // Bind the event to handlers specified as a string of
2199
+ // handler names on the target object
2200
+ function unbindFromStrings(target, entity, evt, methods){
2201
+ var methodNames = methods.split(/\s+/);
2202
+
2203
+ _.each(methodNames,function(methodName) {
2204
+ var method = target[methodName];
2205
+ target.stopListening(entity, evt, method, target);
2206
+ });
2207
+ }
2208
+
2209
+ // Bind the event to a supplied callback function
2210
+ function unbindToFunction(target, entity, evt, method){
2211
+ target.stopListening(entity, evt, method, target);
2212
+ }
2213
+
2214
+
2215
+ // generic looping function
2216
+ function iterateEvents(target, entity, bindings, functionCallback, stringCallback){
2217
+ if (!entity || !bindings) { return; }
2218
+
2219
+ // allow the bindings to be a function
2220
+ if (_.isFunction(bindings)){
2221
+ bindings = bindings.call(target);
2222
+ }
2223
+
2224
+ // iterate the bindings and bind them
2225
+ _.each(bindings, function(methods, evt){
2226
+
2227
+ // allow for a function as the handler,
2228
+ // or a list of event names as a string
2229
+ if (_.isFunction(methods)){
2230
+ functionCallback(target, entity, evt, methods);
2231
+ } else {
2232
+ stringCallback(target, entity, evt, methods);
2233
+ }
2234
+
2235
+ });
2236
+ }
2237
+
2238
+ // Export Public API
2239
+ Marionette.bindEntityEvents = function(target, entity, bindings){
2240
+ iterateEvents(target, entity, bindings, bindToFunction, bindFromStrings);
2241
+ };
2242
+
2243
+ Marionette.unbindEntityEvents = function(target, entity, bindings){
2244
+ iterateEvents(target, entity, bindings, unbindToFunction, unbindFromStrings);
2245
+ };
2246
+
2247
+ })(Marionette);
2248
+
2249
+
2250
+ // Callbacks
2251
+ // ---------
2252
+
2253
+ // A simple way of managing a collection of callbacks
2254
+ // and executing them at a later point in time, using jQuery's
2255
+ // `Deferred` object.
2256
+ Marionette.Callbacks = function(){
2257
+ this._deferred = Marionette.$.Deferred();
2258
+ this._callbacks = [];
2259
+ };
2260
+
2261
+ _.extend(Marionette.Callbacks.prototype, {
2262
+
2263
+ // Add a callback to be executed. Callbacks added here are
2264
+ // guaranteed to execute, even if they are added after the
2265
+ // `run` method is called.
2266
+ add: function(callback, contextOverride){
2267
+ this._callbacks.push({cb: callback, ctx: contextOverride});
2268
+
2269
+ this._deferred.done(function(context, options){
2270
+ if (contextOverride){ context = contextOverride; }
2271
+ callback.call(context, options);
2272
+ });
2273
+ },
2274
+
2275
+ // Run all registered callbacks with the context specified.
2276
+ // Additional callbacks can be added after this has been run
2277
+ // and they will still be executed.
2278
+ run: function(options, context){
2279
+ this._deferred.resolve(context, options);
2280
+ },
2281
+
2282
+ // Resets the list of callbacks to be run, allowing the same list
2283
+ // to be run multiple times - whenever the `run` method is called.
2284
+ reset: function(){
2285
+ var callbacks = this._callbacks;
2286
+ this._deferred = Marionette.$.Deferred();
2287
+ this._callbacks = [];
2288
+
2289
+ _.each(callbacks, function(cb){
2290
+ this.add(cb.cb, cb.ctx);
2291
+ }, this);
2292
+ }
2293
+ });
2294
+
2295
+
2296
+ // Marionette Controller
2297
+ // ---------------------
2298
+ //
2299
+ // A multi-purpose object to use as a controller for
2300
+ // modules and routers, and as a mediator for workflow
2301
+ // and coordination of other objects, views, and more.
2302
+ Marionette.Controller = function(options){
2303
+ this.triggerMethod = Marionette.triggerMethod;
2304
+ this.options = options || {};
2305
+
2306
+ if (_.isFunction(this.initialize)){
2307
+ this.initialize(this.options);
2308
+ }
2309
+ };
2310
+
2311
+ Marionette.Controller.extend = Marionette.extend;
2312
+
2313
+ // Controller Methods
2314
+ // --------------
2315
+
2316
+ // Ensure it can trigger events with Backbone.Events
2317
+ _.extend(Marionette.Controller.prototype, Backbone.Events, {
2318
+ close: function(){
2319
+ this.stopListening();
2320
+ this.triggerMethod("close");
2321
+ this.unbind();
2322
+ }
2323
+ });
2324
+
2325
+ // Region
2326
+ // ------
2327
+ //
2328
+ // Manage the visual regions of your composite application. See
2329
+ // http://lostechies.com/derickbailey/2011/12/12/composite-js-apps-regions-and-region-managers/
2330
+
2331
+ Marionette.Region = function(options){
2332
+ this.options = options || {};
2333
+
2334
+ this.el = Marionette.getOption(this, "el");
2335
+
2336
+ if (!this.el){
2337
+ var err = new Error("An 'el' must be specified for a region.");
2338
+ err.name = "NoElError";
2339
+ throw err;
2340
+ }
2341
+
2342
+ if (this.initialize){
2343
+ var args = Array.prototype.slice.apply(arguments);
2344
+ this.initialize.apply(this, args);
2345
+ }
2346
+ };
2347
+
2348
+
2349
+ // Region Type methods
2350
+ // -------------------
2351
+
2352
+ _.extend(Marionette.Region, {
2353
+
2354
+ // Build an instance of a region by passing in a configuration object
2355
+ // and a default region type to use if none is specified in the config.
2356
+ //
2357
+ // The config object should either be a string as a jQuery DOM selector,
2358
+ // a Region type directly, or an object literal that specifies both
2359
+ // a selector and regionType:
2360
+ //
2361
+ // ```js
2362
+ // {
2363
+ // selector: "#foo",
2364
+ // regionType: MyCustomRegion
2365
+ // }
2366
+ // ```
2367
+ //
2368
+ buildRegion: function(regionConfig, defaultRegionType){
2369
+
2370
+ var regionIsString = (typeof regionConfig === "string");
2371
+ var regionSelectorIsString = (typeof regionConfig.selector === "string");
2372
+ var regionTypeIsUndefined = (typeof regionConfig.regionType === "undefined");
2373
+ var regionIsType = (typeof regionConfig === "function");
2374
+
2375
+ if (!regionIsType && !regionIsString && !regionSelectorIsString) {
2376
+ throw new Error("Region must be specified as a Region type, a selector string or an object with selector property");
2377
+ }
2378
+
2379
+ var selector, RegionType;
2380
+
2381
+ // get the selector for the region
2382
+
2383
+ if (regionIsString) {
2384
+ selector = regionConfig;
2385
+ }
2386
+
2387
+ if (regionConfig.selector) {
2388
+ selector = regionConfig.selector;
2389
+ }
2390
+
2391
+ // get the type for the region
2392
+
2393
+ if (regionIsType){
2394
+ RegionType = regionConfig;
2395
+ }
2396
+
2397
+ if (!regionIsType && regionTypeIsUndefined) {
2398
+ RegionType = defaultRegionType;
2399
+ }
2400
+
2401
+ if (regionConfig.regionType) {
2402
+ RegionType = regionConfig.regionType;
2403
+ }
2404
+
2405
+ // build the region instance
2406
+ var region = new RegionType({
2407
+ el: selector
2408
+ });
2409
+
2410
+ // override the `getEl` function if we have a parentEl
2411
+ // this must be overridden to ensure the selector is found
2412
+ // on the first use of the region. if we try to assign the
2413
+ // region's `el` to `parentEl.find(selector)` in the object
2414
+ // literal to build the region, the element will not be
2415
+ // guaranteed to be in the DOM already, and will cause problems
2416
+ if (regionConfig.parentEl){
2417
+
2418
+ region.getEl = function(selector) {
2419
+ var parentEl = regionConfig.parentEl;
2420
+ if (_.isFunction(parentEl)){
2421
+ parentEl = parentEl();
2422
+ }
2423
+ return parentEl.find(selector);
2424
+ };
2425
+ }
2426
+
2427
+ return region;
2428
+ }
2429
+
2430
+ });
2431
+
2432
+ // Region Instance Methods
2433
+ // -----------------------
2434
+
2435
+ _.extend(Marionette.Region.prototype, Backbone.Events, {
2436
+
2437
+ // Displays a backbone view instance inside of the region.
2438
+ // Handles calling the `render` method for you. Reads content
2439
+ // directly from the `el` attribute. Also calls an optional
2440
+ // `onShow` and `close` method on your view, just after showing
2441
+ // or just before closing the view, respectively.
2442
+ show: function(view){
2443
+
2444
+ this.ensureEl();
2445
+
2446
+ var isViewClosed = view.isClosed || _.isUndefined(view.$el);
2447
+
2448
+ var isDifferentView = view !== this.currentView;
2449
+
2450
+ if (isDifferentView) {
2451
+ this.close();
2452
+ }
2453
+
2454
+ view.render();
2455
+
2456
+ if (isDifferentView || isViewClosed) {
2457
+ this.open(view);
2458
+ }
2459
+
2460
+ this.currentView = view;
2461
+
2462
+ Marionette.triggerMethod.call(this, "show", view);
2463
+ Marionette.triggerMethod.call(view, "show");
2464
+ },
2465
+
2466
+ ensureEl: function(){
2467
+ if (!this.$el || this.$el.length === 0){
2468
+ this.$el = this.getEl(this.el);
2469
+ }
2470
+ },
2471
+
2472
+ // Override this method to change how the region finds the
2473
+ // DOM element that it manages. Return a jQuery selector object.
2474
+ getEl: function(selector){
2475
+ return Marionette.$(selector);
2476
+ },
2477
+
2478
+ // Override this method to change how the new view is
2479
+ // appended to the `$el` that the region is managing
2480
+ open: function(view){
2481
+ this.$el.empty().append(view.el);
2482
+ },
2483
+
2484
+ // Close the current view, if there is one. If there is no
2485
+ // current view, it does nothing and returns immediately.
2486
+ close: function(){
2487
+ var view = this.currentView;
2488
+ if (!view || view.isClosed){ return; }
2489
+
2490
+ // call 'close' or 'remove', depending on which is found
2491
+ if (view.close) { view.close(); }
2492
+ else if (view.remove) { view.remove(); }
2493
+
2494
+ Marionette.triggerMethod.call(this, "close");
2495
+
2496
+ delete this.currentView;
2497
+ },
2498
+
2499
+ // Attach an existing view to the region. This
2500
+ // will not call `render` or `onShow` for the new view,
2501
+ // and will not replace the current HTML for the `el`
2502
+ // of the region.
2503
+ attachView: function(view){
2504
+ this.currentView = view;
2505
+ },
2506
+
2507
+ // Reset the region by closing any existing view and
2508
+ // clearing out the cached `$el`. The next time a view
2509
+ // is shown via this region, the region will re-query the
2510
+ // DOM for the region's `el`.
2511
+ reset: function(){
2512
+ this.close();
2513
+ delete this.$el;
2514
+ }
2515
+ });
2516
+
2517
+ // Copy the `extend` function used by Backbone's classes
2518
+ Marionette.Region.extend = Marionette.extend;
2519
+
2520
+ // Marionette.RegionManager
2521
+ // ------------------------
2522
+ //
2523
+ // Manage one or more related `Marionette.Region` objects.
2524
+ Marionette.RegionManager = (function(Marionette){
2525
+
2526
+ var RegionManager = Marionette.Controller.extend({
2527
+ constructor: function(options){
2528
+ this._regions = {};
2529
+ Marionette.Controller.prototype.constructor.call(this, options);
2530
+ },
2531
+
2532
+ // Add multiple regions using an object literal, where
2533
+ // each key becomes the region name, and each value is
2534
+ // the region definition.
2535
+ addRegions: function(regionDefinitions, defaults){
2536
+ var regions = {};
2537
+
2538
+ _.each(regionDefinitions, function(definition, name){
2539
+ if (typeof definition === "string"){
2540
+ definition = { selector: definition };
2541
+ }
2542
+
2543
+ if (definition.selector){
2544
+ definition = _.defaults({}, definition, defaults);
2545
+ }
2546
+
2547
+ var region = this.addRegion(name, definition);
2548
+ regions[name] = region;
2549
+ }, this);
2550
+
2551
+ return regions;
2552
+ },
2553
+
2554
+ // Add an individual region to the region manager,
2555
+ // and return the region instance
2556
+ addRegion: function(name, definition){
2557
+ var region;
2558
+
2559
+ var isObject = _.isObject(definition);
2560
+ var isString = _.isString(definition);
2561
+ var hasSelector = !!definition.selector;
2562
+
2563
+ if (isString || (isObject && hasSelector)){
2564
+ region = Marionette.Region.buildRegion(definition, Marionette.Region);
2565
+ } else if (_.isFunction(definition)){
2566
+ region = Marionette.Region.buildRegion(definition, Marionette.Region);
2567
+ } else {
2568
+ region = definition;
2569
+ }
2570
+
2571
+ this._store(name, region);
2572
+ this.triggerMethod("region:add", name, region);
2573
+ return region;
2574
+ },
2575
+
2576
+ // Get a region by name
2577
+ get: function(name){
2578
+ return this._regions[name];
2579
+ },
2580
+
2581
+ // Remove a region by name
2582
+ removeRegion: function(name){
2583
+ var region = this._regions[name];
2584
+ this._remove(name, region);
2585
+ },
2586
+
2587
+ // Close all regions in the region manager, and
2588
+ // remove them
2589
+ removeRegions: function(){
2590
+ _.each(this._regions, function(region, name){
2591
+ this._remove(name, region);
2592
+ }, this);
2593
+ },
2594
+
2595
+ // Close all regions in the region manager, but
2596
+ // leave them attached
2597
+ closeRegions: function(){
2598
+ _.each(this._regions, function(region, name){
2599
+ region.close();
2600
+ }, this);
2601
+ },
2602
+
2603
+ // Close all regions and shut down the region
2604
+ // manager entirely
2605
+ close: function(){
2606
+ this.removeRegions();
2607
+ var args = Array.prototype.slice.call(arguments);
2608
+ Marionette.Controller.prototype.close.apply(this, args);
2609
+ },
2610
+
2611
+ // internal method to store regions
2612
+ _store: function(name, region){
2613
+ this._regions[name] = region;
2614
+ this._setLength();
2615
+ },
2616
+
2617
+ // internal method to remove a region
2618
+ _remove: function(name, region){
2619
+ region.close();
2620
+ delete this._regions[name];
2621
+ this._setLength();
2622
+ this.triggerMethod("region:remove", name, region);
2623
+ },
2624
+
2625
+ // set the number of regions current held
2626
+ _setLength: function(){
2627
+ this.length = _.size(this._regions);
2628
+ }
2629
+
2630
+ });
2631
+
2632
+ // Borrowing this code from Backbone.Collection:
2633
+ // http://backbonejs.org/docs/backbone.html#section-106
2634
+ //
2635
+ // Mix in methods from Underscore, for iteration, and other
2636
+ // collection related features.
2637
+ var methods = ['forEach', 'each', 'map', 'find', 'detect', 'filter',
2638
+ 'select', 'reject', 'every', 'all', 'some', 'any', 'include',
2639
+ 'contains', 'invoke', 'toArray', 'first', 'initial', 'rest',
2640
+ 'last', 'without', 'isEmpty', 'pluck'];
2641
+
2642
+ _.each(methods, function(method) {
2643
+ RegionManager.prototype[method] = function() {
2644
+ var regions = _.values(this._regions);
2645
+ var args = [regions].concat(_.toArray(arguments));
2646
+ return _[method].apply(_, args);
2647
+ };
2648
+ });
2649
+
2650
+ return RegionManager;
2651
+ })(Marionette);
2652
+
2653
+
2654
+ // Template Cache
2655
+ // --------------
2656
+
2657
+ // Manage templates stored in `<script>` blocks,
2658
+ // caching them for faster access.
2659
+ Marionette.TemplateCache = function(templateId){
2660
+ this.templateId = templateId;
2661
+ };
2662
+
2663
+ // TemplateCache object-level methods. Manage the template
2664
+ // caches from these method calls instead of creating
2665
+ // your own TemplateCache instances
2666
+ _.extend(Marionette.TemplateCache, {
2667
+ templateCaches: {},
2668
+
2669
+ // Get the specified template by id. Either
2670
+ // retrieves the cached version, or loads it
2671
+ // from the DOM.
2672
+ get: function(templateId){
2673
+ var cachedTemplate = this.templateCaches[templateId];
2674
+
2675
+ if (!cachedTemplate){
2676
+ cachedTemplate = new Marionette.TemplateCache(templateId);
2677
+ this.templateCaches[templateId] = cachedTemplate;
2678
+ }
2679
+
2680
+ return cachedTemplate.load();
2681
+ },
2682
+
2683
+ // Clear templates from the cache. If no arguments
2684
+ // are specified, clears all templates:
2685
+ // `clear()`
2686
+ //
2687
+ // If arguments are specified, clears each of the
2688
+ // specified templates from the cache:
2689
+ // `clear("#t1", "#t2", "...")`
2690
+ clear: function(){
2691
+ var i;
2692
+ var args = slice(arguments);
2693
+ var length = args.length;
2694
+
2695
+ if (length > 0){
2696
+ for(i=0; i<length; i++){
2697
+ delete this.templateCaches[args[i]];
2698
+ }
2699
+ } else {
2700
+ this.templateCaches = {};
2701
+ }
2702
+ }
2703
+ });
2704
+
2705
+ // TemplateCache instance methods, allowing each
2706
+ // template cache object to manage its own state
2707
+ // and know whether or not it has been loaded
2708
+ _.extend(Marionette.TemplateCache.prototype, {
2709
+
2710
+ // Internal method to load the template
2711
+ load: function(){
2712
+ // Guard clause to prevent loading this template more than once
2713
+ if (this.compiledTemplate){
2714
+ return this.compiledTemplate;
2715
+ }
2716
+
2717
+ // Load the template and compile it
2718
+ var template = this.loadTemplate(this.templateId);
2719
+ this.compiledTemplate = this.compileTemplate(template);
2720
+
2721
+ return this.compiledTemplate;
2722
+ },
2723
+
2724
+ // Load a template from the DOM, by default. Override
2725
+ // this method to provide your own template retrieval
2726
+ // For asynchronous loading with AMD/RequireJS, consider
2727
+ // using a template-loader plugin as described here:
2728
+ // https://github.com/marionettejs/backbone.marionette/wiki/Using-marionette-with-requirejs
2729
+ loadTemplate: function(templateId){
2730
+ var template = Marionette.$(templateId).html();
2731
+
2732
+ if (!template || template.length === 0){
2733
+ throwError("Could not find template: '" + templateId + "'", "NoTemplateError");
2734
+ }
2735
+
2736
+ return template;
2737
+ },
2738
+
2739
+ // Pre-compile the template before caching it. Override
2740
+ // this method if you do not need to pre-compile a template
2741
+ // (JST / RequireJS for example) or if you want to change
2742
+ // the template engine used (Handebars, etc).
2743
+ compileTemplate: function(rawTemplate){
2744
+ return _.template(rawTemplate);
2745
+ }
2746
+ });
2747
+
2748
+
2749
+ // Renderer
2750
+ // --------
2751
+
2752
+ // Render a template with data by passing in the template
2753
+ // selector and the data to render.
2754
+ Marionette.Renderer = {
2755
+
2756
+ // Render a template with data. The `template` parameter is
2757
+ // passed to the `TemplateCache` object to retrieve the
2758
+ // template function. Override this method to provide your own
2759
+ // custom rendering and template handling for all of Marionette.
2760
+ render: function(template, data){
2761
+
2762
+ if (!template) {
2763
+ var error = new Error("Cannot render the template since it's false, null or undefined.");
2764
+ error.name = "TemplateNotFoundError";
2765
+ throw error;
2766
+ }
2767
+
2768
+ var templateFunc;
2769
+ if (typeof template === "function"){
2770
+ templateFunc = template;
2771
+ } else {
2772
+ templateFunc = Marionette.TemplateCache.get(template);
2773
+ }
2774
+
2775
+ return templateFunc(data);
2776
+ }
2777
+ };
2778
+
2779
+
2780
+
2781
+ // Marionette.View
2782
+ // ---------------
2783
+
2784
+ // The core view type that other Marionette views extend from.
2785
+ Marionette.View = Backbone.View.extend({
2786
+
2787
+ constructor: function(options){
2788
+ _.bindAll(this, "render");
2789
+
2790
+ var args = Array.prototype.slice.apply(arguments);
2791
+
2792
+ // this exposes view options to the view initializer
2793
+ // this is a backfill since backbone removed the assignment
2794
+ // of this.options
2795
+ // at some point however this may be removed
2796
+ this.options = _.extend({}, this.options, options);
2797
+
2798
+ // parses out the @ui DSL for events
2799
+ this.events = this.normalizeUIKeys(_.result(this, 'events'));
2800
+ Backbone.View.prototype.constructor.apply(this, args);
2801
+
2802
+ Marionette.MonitorDOMRefresh(this);
2803
+ this.listenTo(this, "show", this.onShowCalled, this);
2804
+ },
2805
+
2806
+ // import the "triggerMethod" to trigger events with corresponding
2807
+ // methods if the method exists
2808
+ triggerMethod: Marionette.triggerMethod,
2809
+
2810
+ // Get the template for this view
2811
+ // instance. You can set a `template` attribute in the view
2812
+ // definition or pass a `template: "whatever"` parameter in
2813
+ // to the constructor options.
2814
+ getTemplate: function(){
2815
+ return Marionette.getOption(this, "template");
2816
+ },
2817
+
2818
+ // Mix in template helper methods. Looks for a
2819
+ // `templateHelpers` attribute, which can either be an
2820
+ // object literal, or a function that returns an object
2821
+ // literal. All methods and attributes from this object
2822
+ // are copies to the object passed in.
2823
+ mixinTemplateHelpers: function(target){
2824
+ target = target || {};
2825
+ var templateHelpers = Marionette.getOption(this, "templateHelpers");
2826
+ if (_.isFunction(templateHelpers)){
2827
+ templateHelpers = templateHelpers.call(this);
2828
+ }
2829
+ return _.extend(target, templateHelpers);
2830
+ },
2831
+
2832
+ // allows for the use of the @ui. syntax within
2833
+ // a given key for triggers and events
2834
+ // swaps the @ui with the associated selector
2835
+ normalizeUIKeys: function(hash) {
2836
+ if (typeof(hash) === "undefined") {
2837
+ return;
2838
+ }
2839
+
2840
+ _.each(_.keys(hash), function(v) {
2841
+ var split = v.split("@ui.");
2842
+ if (split.length === 2) {
2843
+ hash[split[0]+this.ui[split[1]]] = hash[v];
2844
+ delete hash[v];
2845
+ }
2846
+ }, this);
2847
+
2848
+ return hash;
2849
+ },
2850
+
2851
+ // Configure `triggers` to forward DOM events to view
2852
+ // events. `triggers: {"click .foo": "do:foo"}`
2853
+ configureTriggers: function(){
2854
+ if (!this.triggers) { return; }
2855
+
2856
+ var triggerEvents = {};
2857
+
2858
+ // Allow `triggers` to be configured as a function
2859
+ var triggers = this.normalizeUIKeys(_.result(this, "triggers"));
2860
+
2861
+ // Configure the triggers, prevent default
2862
+ // action and stop propagation of DOM events
2863
+ _.each(triggers, function(value, key){
2864
+
2865
+ var hasOptions = _.isObject(value);
2866
+ var eventName = hasOptions ? value.event : value;
2867
+
2868
+ // build the event handler function for the DOM event
2869
+ triggerEvents[key] = function(e){
2870
+
2871
+ // stop the event in its tracks
2872
+ if (e) {
2873
+ var prevent = e.preventDefault;
2874
+ var stop = e.stopPropagation;
2875
+
2876
+ var shouldPrevent = hasOptions ? value.preventDefault : prevent;
2877
+ var shouldStop = hasOptions ? value.stopPropagation : stop;
2878
+
2879
+ if (shouldPrevent && prevent) { prevent.apply(e); }
2880
+ if (shouldStop && stop) { stop.apply(e); }
2881
+ }
2882
+
2883
+ // build the args for the event
2884
+ var args = {
2885
+ view: this,
2886
+ model: this.model,
2887
+ collection: this.collection
2888
+ };
2889
+
2890
+ // trigger the event
2891
+ this.triggerMethod(eventName, args);
2892
+ };
2893
+
2894
+ }, this);
2895
+
2896
+ return triggerEvents;
2897
+ },
2898
+
2899
+ // Overriding Backbone.View's delegateEvents to handle
2900
+ // the `triggers`, `modelEvents`, and `collectionEvents` configuration
2901
+ delegateEvents: function(events){
2902
+ this._delegateDOMEvents(events);
2903
+ Marionette.bindEntityEvents(this, this.model, Marionette.getOption(this, "modelEvents"));
2904
+ Marionette.bindEntityEvents(this, this.collection, Marionette.getOption(this, "collectionEvents"));
2905
+ },
2906
+
2907
+ // internal method to delegate DOM events and triggers
2908
+ _delegateDOMEvents: function(events){
2909
+ events = events || this.events;
2910
+ if (_.isFunction(events)){ events = events.call(this); }
2911
+
2912
+ var combinedEvents = {};
2913
+ var triggers = this.configureTriggers();
2914
+ _.extend(combinedEvents, events, triggers);
2915
+
2916
+ Backbone.View.prototype.delegateEvents.call(this, combinedEvents);
2917
+ },
2918
+
2919
+ // Overriding Backbone.View's undelegateEvents to handle unbinding
2920
+ // the `triggers`, `modelEvents`, and `collectionEvents` config
2921
+ undelegateEvents: function(){
2922
+ var args = Array.prototype.slice.call(arguments);
2923
+ Backbone.View.prototype.undelegateEvents.apply(this, args);
2924
+
2925
+ Marionette.unbindEntityEvents(this, this.model, Marionette.getOption(this, "modelEvents"));
2926
+ Marionette.unbindEntityEvents(this, this.collection, Marionette.getOption(this, "collectionEvents"));
2927
+ },
2928
+
2929
+ // Internal method, handles the `show` event.
2930
+ onShowCalled: function(){},
2931
+
2932
+ // Default `close` implementation, for removing a view from the
2933
+ // DOM and unbinding it. Regions will call this method
2934
+ // for you. You can specify an `onClose` method in your view to
2935
+ // add custom code that is called after the view is closed.
2936
+ close: function(){
2937
+ if (this.isClosed) { return; }
2938
+
2939
+ // allow the close to be stopped by returning `false`
2940
+ // from the `onBeforeClose` method
2941
+ var shouldClose = this.triggerMethod("before:close");
2942
+ if (shouldClose === false){
2943
+ return;
2944
+ }
2945
+
2946
+ // mark as closed before doing the actual close, to
2947
+ // prevent infinite loops within "close" event handlers
2948
+ // that are trying to close other views
2949
+ this.isClosed = true;
2950
+ this.triggerMethod("close");
2951
+
2952
+ // unbind UI elements
2953
+ this.unbindUIElements();
2954
+
2955
+ // remove the view from the DOM
2956
+ this.remove();
2957
+ },
2958
+
2959
+ // This method binds the elements specified in the "ui" hash inside the view's code with
2960
+ // the associated jQuery selectors.
2961
+ bindUIElements: function(){
2962
+ if (!this.ui) { return; }
2963
+
2964
+ // store the ui hash in _uiBindings so they can be reset later
2965
+ // and so re-rendering the view will be able to find the bindings
2966
+ if (!this._uiBindings){
2967
+ this._uiBindings = this.ui;
2968
+ }
2969
+
2970
+ // get the bindings result, as a function or otherwise
2971
+ var bindings = _.result(this, "_uiBindings");
2972
+
2973
+ // empty the ui so we don't have anything to start with
2974
+ this.ui = {};
2975
+
2976
+ // bind each of the selectors
2977
+ _.each(_.keys(bindings), function(key) {
2978
+ var selector = bindings[key];
2979
+ this.ui[key] = this.$(selector);
2980
+ }, this);
2981
+ },
2982
+
2983
+ // This method unbinds the elements specified in the "ui" hash
2984
+ unbindUIElements: function(){
2985
+ if (!this.ui || !this._uiBindings){ return; }
2986
+
2987
+ // delete all of the existing ui bindings
2988
+ _.each(this.ui, function($el, name){
2989
+ delete this.ui[name];
2990
+ }, this);
2991
+
2992
+ // reset the ui element to the original bindings configuration
2993
+ this.ui = this._uiBindings;
2994
+ delete this._uiBindings;
2995
+ }
2996
+ });
2997
+
2998
+ // Item View
2999
+ // ---------
3000
+
3001
+ // A single item view implementation that contains code for rendering
3002
+ // with underscore.js templates, serializing the view's model or collection,
3003
+ // and calling several methods on extended views, such as `onRender`.
3004
+ Marionette.ItemView = Marionette.View.extend({
3005
+
3006
+ // Setting up the inheritance chain which allows changes to
3007
+ // Marionette.View.prototype.constructor which allows overriding
3008
+ constructor: function(){
3009
+ Marionette.View.prototype.constructor.apply(this, slice(arguments));
3010
+ },
3011
+
3012
+ // Serialize the model or collection for the view. If a model is
3013
+ // found, `.toJSON()` is called. If a collection is found, `.toJSON()`
3014
+ // is also called, but is used to populate an `items` array in the
3015
+ // resulting data. If both are found, defaults to the model.
3016
+ // You can override the `serializeData` method in your own view
3017
+ // definition, to provide custom serialization for your view's data.
3018
+ serializeData: function(){
3019
+ var data = {};
3020
+
3021
+ if (this.model) {
3022
+ data = this.model.toJSON();
3023
+ }
3024
+ else if (this.collection) {
3025
+ data = { items: this.collection.toJSON() };
3026
+ }
3027
+
3028
+ return data;
3029
+ },
3030
+
3031
+ // Render the view, defaulting to underscore.js templates.
3032
+ // You can override this in your view definition to provide
3033
+ // a very specific rendering for your view. In general, though,
3034
+ // you should override the `Marionette.Renderer` object to
3035
+ // change how Marionette renders views.
3036
+ render: function(){
3037
+ this.isClosed = false;
3038
+
3039
+ this.triggerMethod("before:render", this);
3040
+ this.triggerMethod("item:before:render", this);
3041
+
3042
+ var data = this.serializeData();
3043
+ data = this.mixinTemplateHelpers(data);
3044
+
3045
+ var template = this.getTemplate();
3046
+ var html = Marionette.Renderer.render(template, data);
3047
+
3048
+ this.$el.html(html);
3049
+ this.bindUIElements();
3050
+
3051
+ this.triggerMethod("render", this);
3052
+ this.triggerMethod("item:rendered", this);
3053
+
3054
+ return this;
3055
+ },
3056
+
3057
+ // Override the default close event to add a few
3058
+ // more events that are triggered.
3059
+ close: function(){
3060
+ if (this.isClosed){ return; }
3061
+
3062
+ this.triggerMethod('item:before:close');
3063
+
3064
+ Marionette.View.prototype.close.apply(this, slice(arguments));
3065
+
3066
+ this.triggerMethod('item:closed');
3067
+ }
3068
+ });
3069
+
3070
+ // Collection View
3071
+ // ---------------
3072
+
3073
+ // A view that iterates over a Backbone.Collection
3074
+ // and renders an individual ItemView for each model.
3075
+ Marionette.CollectionView = Marionette.View.extend({
3076
+ // used as the prefix for item view events
3077
+ // that are forwarded through the collectionview
3078
+ itemViewEventPrefix: "itemview",
3079
+
3080
+ // constructor
3081
+ constructor: function(options){
3082
+ this._initChildViewStorage();
3083
+
3084
+ Marionette.View.prototype.constructor.apply(this, slice(arguments));
3085
+
3086
+ this._initialEvents();
3087
+ this.initRenderBuffer();
3088
+ },
3089
+
3090
+ // Instead of inserting elements one by one into the page,
3091
+ // it's much more performant to insert elements into a document
3092
+ // fragment and then insert that document fragment into the page
3093
+ initRenderBuffer: function() {
3094
+ this.elBuffer = document.createDocumentFragment();
3095
+ },
3096
+
3097
+ startBuffering: function() {
3098
+ this.initRenderBuffer();
3099
+ this.isBuffering = true;
3100
+ },
3101
+
3102
+ endBuffering: function() {
3103
+ this.appendBuffer(this, this.elBuffer);
3104
+ this.initRenderBuffer();
3105
+ this.isBuffering = false;
3106
+ },
3107
+
3108
+ // Configured the initial events that the collection view
3109
+ // binds to. Override this method to prevent the initial
3110
+ // events, or to add your own initial events.
3111
+ _initialEvents: function(){
3112
+ if (this.collection){
3113
+ this.listenTo(this.collection, "add", this.addChildView, this);
3114
+ this.listenTo(this.collection, "remove", this.removeItemView, this);
3115
+ this.listenTo(this.collection, "reset", this.render, this);
3116
+ }
3117
+ },
3118
+
3119
+ // Handle a child item added to the collection
3120
+ addChildView: function(item, collection, options){
3121
+ this.closeEmptyView();
3122
+ var ItemView = this.getItemView(item);
3123
+ var index = this.collection.indexOf(item);
3124
+ this.addItemView(item, ItemView, index);
3125
+ },
3126
+
3127
+ // Override from `Marionette.View` to guarantee the `onShow` method
3128
+ // of child views is called.
3129
+ onShowCalled: function(){
3130
+ this.children.each(function(child){
3131
+ Marionette.triggerMethod.call(child, "show");
3132
+ });
3133
+ },
3134
+
3135
+ // Internal method to trigger the before render callbacks
3136
+ // and events
3137
+ triggerBeforeRender: function(){
3138
+ this.triggerMethod("before:render", this);
3139
+ this.triggerMethod("collection:before:render", this);
3140
+ },
3141
+
3142
+ // Internal method to trigger the rendered callbacks and
3143
+ // events
3144
+ triggerRendered: function(){
3145
+ this.triggerMethod("render", this);
3146
+ this.triggerMethod("collection:rendered", this);
3147
+ },
3148
+
3149
+ // Render the collection of items. Override this method to
3150
+ // provide your own implementation of a render function for
3151
+ // the collection view.
3152
+ render: function(){
3153
+ this.isClosed = false;
3154
+ this.triggerBeforeRender();
3155
+ this._renderChildren();
3156
+ this.triggerRendered();
3157
+ return this;
3158
+ },
3159
+
3160
+ // Internal method. Separated so that CompositeView can have
3161
+ // more control over events being triggered, around the rendering
3162
+ // process
3163
+ _renderChildren: function(){
3164
+ this.startBuffering();
3165
+
3166
+ this.closeEmptyView();
3167
+ this.closeChildren();
3168
+
3169
+ if (this.collection && this.collection.length > 0) {
3170
+ this.showCollection();
3171
+ } else {
3172
+ this.showEmptyView();
3173
+ }
3174
+
3175
+ this.endBuffering();
3176
+ },
3177
+
3178
+ // Internal method to loop through each item in the
3179
+ // collection view and show it
3180
+ showCollection: function(){
3181
+ var ItemView;
3182
+ this.collection.each(function(item, index){
3183
+ ItemView = this.getItemView(item);
3184
+ this.addItemView(item, ItemView, index);
3185
+ }, this);
3186
+ },
3187
+
3188
+ // Internal method to show an empty view in place of
3189
+ // a collection of item views, when the collection is
3190
+ // empty
3191
+ showEmptyView: function(){
3192
+ var EmptyView = this.getEmptyView();
3193
+
3194
+ if (EmptyView && !this._showingEmptyView){
3195
+ this._showingEmptyView = true;
3196
+ var model = new Backbone.Model();
3197
+ this.addItemView(model, EmptyView, 0);
3198
+ }
3199
+ },
3200
+
3201
+ // Internal method to close an existing emptyView instance
3202
+ // if one exists. Called when a collection view has been
3203
+ // rendered empty, and then an item is added to the collection.
3204
+ closeEmptyView: function(){
3205
+ if (this._showingEmptyView){
3206
+ this.closeChildren();
3207
+ delete this._showingEmptyView;
3208
+ }
3209
+ },
3210
+
3211
+ // Retrieve the empty view type
3212
+ getEmptyView: function(){
3213
+ return Marionette.getOption(this, "emptyView");
3214
+ },
3215
+
3216
+ // Retrieve the itemView type, either from `this.options.itemView`
3217
+ // or from the `itemView` in the object definition. The "options"
3218
+ // takes precedence.
3219
+ getItemView: function(item){
3220
+ var itemView = Marionette.getOption(this, "itemView");
3221
+
3222
+ if (!itemView){
3223
+ throwError("An `itemView` must be specified", "NoItemViewError");
3224
+ }
3225
+
3226
+ return itemView;
3227
+ },
3228
+
3229
+ // Render the child item's view and add it to the
3230
+ // HTML for the collection view.
3231
+ addItemView: function(item, ItemView, index){
3232
+ // get the itemViewOptions if any were specified
3233
+ var itemViewOptions = Marionette.getOption(this, "itemViewOptions");
3234
+ if (_.isFunction(itemViewOptions)){
3235
+ itemViewOptions = itemViewOptions.call(this, item, index);
3236
+ }
3237
+
3238
+ // build the view
3239
+ var view = this.buildItemView(item, ItemView, itemViewOptions);
3240
+
3241
+ // set up the child view event forwarding
3242
+ this.addChildViewEventForwarding(view);
3243
+
3244
+ // this view is about to be added
3245
+ this.triggerMethod("before:item:added", view);
3246
+
3247
+ // Store the child view itself so we can properly
3248
+ // remove and/or close it later
3249
+ this.children.add(view);
3250
+
3251
+ // Render it and show it
3252
+ this.renderItemView(view, index);
3253
+
3254
+ // call the "show" method if the collection view
3255
+ // has already been shown
3256
+ if (this._isShown){
3257
+ Marionette.triggerMethod.call(view, "show");
3258
+ }
3259
+
3260
+ // this view was added
3261
+ this.triggerMethod("after:item:added", view);
3262
+ },
3263
+
3264
+ // Set up the child view event forwarding. Uses an "itemview:"
3265
+ // prefix in front of all forwarded events.
3266
+ addChildViewEventForwarding: function(view){
3267
+ var prefix = Marionette.getOption(this, "itemViewEventPrefix");
3268
+
3269
+ // Forward all child item view events through the parent,
3270
+ // prepending "itemview:" to the event name
3271
+ this.listenTo(view, "all", function(){
3272
+ var args = slice(arguments);
3273
+ args[0] = prefix + ":" + args[0];
3274
+ args.splice(1, 0, view);
3275
+
3276
+ Marionette.triggerMethod.apply(this, args);
3277
+ }, this);
3278
+ },
3279
+
3280
+ // render the item view
3281
+ renderItemView: function(view, index) {
3282
+ view.render();
3283
+ this.appendHtml(this, view, index);
3284
+ },
3285
+
3286
+ // Build an `itemView` for every model in the collection.
3287
+ buildItemView: function(item, ItemViewType, itemViewOptions){
3288
+ var options = _.extend({model: item}, itemViewOptions);
3289
+ return new ItemViewType(options);
3290
+ },
3291
+
3292
+ // get the child view by item it holds, and remove it
3293
+ removeItemView: function(item){
3294
+ var view = this.children.findByModel(item);
3295
+ this.removeChildView(view);
3296
+ this.checkEmpty();
3297
+ },
3298
+
3299
+ // Remove the child view and close it
3300
+ removeChildView: function(view){
3301
+
3302
+ // shut down the child view properly,
3303
+ // including events that the collection has from it
3304
+ if (view){
3305
+ this.stopListening(view);
3306
+
3307
+ // call 'close' or 'remove', depending on which is found
3308
+ if (view.close) { view.close(); }
3309
+ else if (view.remove) { view.remove(); }
3310
+
3311
+ this.children.remove(view);
3312
+ }
3313
+
3314
+ this.triggerMethod("item:removed", view);
3315
+ },
3316
+
3317
+ // helper to show the empty view if the collection is empty
3318
+ checkEmpty: function() {
3319
+ // check if we're empty now, and if we are, show the
3320
+ // empty view
3321
+ if (!this.collection || this.collection.length === 0){
3322
+ this.showEmptyView();
3323
+ }
3324
+ },
3325
+
3326
+ // You might need to override this if you've overridden appendHtml
3327
+ appendBuffer: function(collectionView, buffer) {
3328
+ collectionView.$el.append(buffer);
3329
+ },
3330
+
3331
+ // Append the HTML to the collection's `el`.
3332
+ // Override this method to do something other
3333
+ // then `.append`.
3334
+ appendHtml: function(collectionView, itemView, index){
3335
+ if (collectionView.isBuffering) {
3336
+ // buffering happens on reset events and initial renders
3337
+ // in order to reduce the number of inserts into the
3338
+ // document, which are expensive.
3339
+ collectionView.elBuffer.appendChild(itemView.el);
3340
+ }
3341
+ else {
3342
+ // If we've already rendered the main collection, just
3343
+ // append the new items directly into the element.
3344
+ collectionView.$el.append(itemView.el);
3345
+ }
3346
+ },
3347
+
3348
+ // Internal method to set up the `children` object for
3349
+ // storing all of the child views
3350
+ _initChildViewStorage: function(){
3351
+ this.children = new Backbone.ChildViewContainer();
3352
+ },
3353
+
3354
+ // Handle cleanup and other closing needs for
3355
+ // the collection of views.
3356
+ close: function(){
3357
+ if (this.isClosed){ return; }
3358
+
3359
+ this.triggerMethod("collection:before:close");
3360
+ this.closeChildren();
3361
+ this.triggerMethod("collection:closed");
3362
+
3363
+ Marionette.View.prototype.close.apply(this, slice(arguments));
3364
+ },
3365
+
3366
+ // Close the child views that this collection view
3367
+ // is holding on to, if any
3368
+ closeChildren: function(){
3369
+ this.children.each(function(child){
3370
+ this.removeChildView(child);
3371
+ }, this);
3372
+ this.checkEmpty();
3373
+ }
3374
+ });
3375
+
3376
+
3377
+ // Composite View
3378
+ // --------------
3379
+
3380
+ // Used for rendering a branch-leaf, hierarchical structure.
3381
+ // Extends directly from CollectionView and also renders an
3382
+ // an item view as `modelView`, for the top leaf
3383
+ Marionette.CompositeView = Marionette.CollectionView.extend({
3384
+
3385
+ // Setting up the inheritance chain which allows changes to
3386
+ // Marionette.CollectionView.prototype.constructor which allows overriding
3387
+ constructor: function(){
3388
+ Marionette.CollectionView.prototype.constructor.apply(this, slice(arguments));
3389
+ },
3390
+
3391
+ // Configured the initial events that the composite view
3392
+ // binds to. Override this method to prevent the initial
3393
+ // events, or to add your own initial events.
3394
+ _initialEvents: function(){
3395
+
3396
+ // Bind only after composite view in rendered to avoid adding child views
3397
+ // to unexisting itemViewContainer
3398
+ this.once('render', function () {
3399
+ if (this.collection){
3400
+ this.listenTo(this.collection, "add", this.addChildView, this);
3401
+ this.listenTo(this.collection, "remove", this.removeItemView, this);
3402
+ this.listenTo(this.collection, "reset", this._renderChildren, this);
3403
+ }
3404
+ });
3405
+
3406
+ },
3407
+
3408
+ // Retrieve the `itemView` to be used when rendering each of
3409
+ // the items in the collection. The default is to return
3410
+ // `this.itemView` or Marionette.CompositeView if no `itemView`
3411
+ // has been defined
3412
+ getItemView: function(item){
3413
+ var itemView = Marionette.getOption(this, "itemView") || this.constructor;
3414
+
3415
+ if (!itemView){
3416
+ throwError("An `itemView` must be specified", "NoItemViewError");
3417
+ }
3418
+
3419
+ return itemView;
3420
+ },
3421
+
3422
+ // Serialize the collection for the view.
3423
+ // You can override the `serializeData` method in your own view
3424
+ // definition, to provide custom serialization for your view's data.
3425
+ serializeData: function(){
3426
+ var data = {};
3427
+
3428
+ if (this.model){
3429
+ data = this.model.toJSON();
3430
+ }
3431
+
3432
+ return data;
3433
+ },
3434
+
3435
+ // Renders the model once, and the collection once. Calling
3436
+ // this again will tell the model's view to re-render itself
3437
+ // but the collection will not re-render.
3438
+ render: function(){
3439
+ this.isRendered = true;
3440
+ this.isClosed = false;
3441
+ this.resetItemViewContainer();
3442
+
3443
+ this.triggerBeforeRender();
3444
+ var html = this.renderModel();
3445
+ this.$el.html(html);
3446
+ // the ui bindings is done here and not at the end of render since they
3447
+ // will not be available until after the model is rendered, but should be
3448
+ // available before the collection is rendered.
3449
+ this.bindUIElements();
3450
+ this.triggerMethod("composite:model:rendered");
3451
+
3452
+ this._renderChildren();
3453
+
3454
+ this.triggerMethod("composite:rendered");
3455
+ this.triggerRendered();
3456
+ return this;
3457
+ },
3458
+
3459
+ _renderChildren: function(){
3460
+ if (this.isRendered){
3461
+ Marionette.CollectionView.prototype._renderChildren.call(this);
3462
+ this.triggerMethod("composite:collection:rendered");
3463
+ }
3464
+ },
3465
+
3466
+ // Render an individual model, if we have one, as
3467
+ // part of a composite view (branch / leaf). For example:
3468
+ // a treeview.
3469
+ renderModel: function(){
3470
+ var data = {};
3471
+ data = this.serializeData();
3472
+ data = this.mixinTemplateHelpers(data);
3473
+
3474
+ var template = this.getTemplate();
3475
+ return Marionette.Renderer.render(template, data);
3476
+ },
3477
+
3478
+
3479
+ // You might need to override this if you've overridden appendHtml
3480
+ appendBuffer: function(compositeView, buffer) {
3481
+ var $container = this.getItemViewContainer(compositeView);
3482
+ $container.append(buffer);
3483
+ },
3484
+
3485
+ // Appends the `el` of itemView instances to the specified
3486
+ // `itemViewContainer` (a jQuery selector). Override this method to
3487
+ // provide custom logic of how the child item view instances have their
3488
+ // HTML appended to the composite view instance.
3489
+ appendHtml: function(compositeView, itemView, index){
3490
+ if (compositeView.isBuffering) {
3491
+ compositeView.elBuffer.appendChild(itemView.el);
3492
+ }
3493
+ else {
3494
+ // If we've already rendered the main collection, just
3495
+ // append the new items directly into the element.
3496
+ var $container = this.getItemViewContainer(compositeView);
3497
+ $container.append(itemView.el);
3498
+ }
3499
+ },
3500
+
3501
+
3502
+ // Internal method to ensure an `$itemViewContainer` exists, for the
3503
+ // `appendHtml` method to use.
3504
+ getItemViewContainer: function(containerView){
3505
+ if ("$itemViewContainer" in containerView){
3506
+ return containerView.$itemViewContainer;
3507
+ }
3508
+
3509
+ var container;
3510
+ var itemViewContainer = Marionette.getOption(containerView, "itemViewContainer");
3511
+ if (itemViewContainer){
3512
+
3513
+ var selector = _.isFunction(itemViewContainer) ? itemViewContainer() : itemViewContainer;
3514
+ container = containerView.$(selector);
3515
+ if (container.length <= 0) {
3516
+ throwError("The specified `itemViewContainer` was not found: " + containerView.itemViewContainer, "ItemViewContainerMissingError");
3517
+ }
3518
+
3519
+ } else {
3520
+ container = containerView.$el;
3521
+ }
3522
+
3523
+ containerView.$itemViewContainer = container;
3524
+ return container;
3525
+ },
3526
+
3527
+ // Internal method to reset the `$itemViewContainer` on render
3528
+ resetItemViewContainer: function(){
3529
+ if (this.$itemViewContainer){
3530
+ delete this.$itemViewContainer;
3531
+ }
3532
+ }
3533
+ });
3534
+
3535
+
3536
+ // Layout
3537
+ // ------
3538
+
3539
+ // Used for managing application layouts, nested layouts and
3540
+ // multiple regions within an application or sub-application.
3541
+ //
3542
+ // A specialized view type that renders an area of HTML and then
3543
+ // attaches `Region` instances to the specified `regions`.
3544
+ // Used for composite view management and sub-application areas.
3545
+ Marionette.Layout = Marionette.ItemView.extend({
3546
+ regionType: Marionette.Region,
3547
+
3548
+ // Ensure the regions are available when the `initialize` method
3549
+ // is called.
3550
+ constructor: function (options) {
3551
+ options = options || {};
3552
+
3553
+ this._firstRender = true;
3554
+ this._initializeRegions(options);
3555
+
3556
+ Marionette.ItemView.prototype.constructor.call(this, options);
3557
+ },
3558
+
3559
+ // Layout's render will use the existing region objects the
3560
+ // first time it is called. Subsequent calls will close the
3561
+ // views that the regions are showing and then reset the `el`
3562
+ // for the regions to the newly rendered DOM elements.
3563
+ render: function(){
3564
+
3565
+ if (this.isClosed){
3566
+ // a previously closed layout means we need to
3567
+ // completely re-initialize the regions
3568
+ this._initializeRegions();
3569
+ }
3570
+ if (this._firstRender) {
3571
+ // if this is the first render, don't do anything to
3572
+ // reset the regions
3573
+ this._firstRender = false;
3574
+ } else if (!this.isClosed){
3575
+ // If this is not the first render call, then we need to
3576
+ // re-initializing the `el` for each region
3577
+ this._reInitializeRegions();
3578
+ }
3579
+
3580
+ var args = Array.prototype.slice.apply(arguments);
3581
+ var result = Marionette.ItemView.prototype.render.apply(this, args);
3582
+
3583
+ return result;
3584
+ },
3585
+
3586
+ // Handle closing regions, and then close the view itself.
3587
+ close: function () {
3588
+ if (this.isClosed){ return; }
3589
+ this.regionManager.close();
3590
+ var args = Array.prototype.slice.apply(arguments);
3591
+ Marionette.ItemView.prototype.close.apply(this, args);
3592
+ },
3593
+
3594
+ // Add a single region, by name, to the layout
3595
+ addRegion: function(name, definition){
3596
+ var regions = {};
3597
+ regions[name] = definition;
3598
+ return this._buildRegions(regions)[name];
3599
+ },
3600
+
3601
+ // Add multiple regions as a {name: definition, name2: def2} object literal
3602
+ addRegions: function(regions){
3603
+ this.regions = _.extend({}, this.regions, regions);
3604
+ return this._buildRegions(regions);
3605
+ },
3606
+
3607
+ // Remove a single region from the Layout, by name
3608
+ removeRegion: function(name){
3609
+ delete this.regions[name];
3610
+ return this.regionManager.removeRegion(name);
3611
+ },
3612
+
3613
+ // internal method to build regions
3614
+ _buildRegions: function(regions){
3615
+ var that = this;
3616
+
3617
+ var defaults = {
3618
+ regionType: Marionette.getOption(this, "regionType"),
3619
+ parentEl: function(){ return that.$el; }
3620
+ };
3621
+
3622
+ return this.regionManager.addRegions(regions, defaults);
3623
+ },
3624
+
3625
+ // Internal method to initialize the regions that have been defined in a
3626
+ // `regions` attribute on this layout.
3627
+ _initializeRegions: function (options) {
3628
+ var regions;
3629
+ this._initRegionManager();
3630
+
3631
+ if (_.isFunction(this.regions)) {
3632
+ regions = this.regions(options);
3633
+ } else {
3634
+ regions = this.regions || {};
3635
+ }
3636
+
3637
+ this.addRegions(regions);
3638
+ },
3639
+
3640
+ // Internal method to re-initialize all of the regions by updating the `el` that
3641
+ // they point to
3642
+ _reInitializeRegions: function(){
3643
+ this.regionManager.closeRegions();
3644
+ this.regionManager.each(function(region){
3645
+ region.reset();
3646
+ });
3647
+ },
3648
+
3649
+ // Internal method to initialize the region manager
3650
+ // and all regions in it
3651
+ _initRegionManager: function(){
3652
+ this.regionManager = new Marionette.RegionManager();
3653
+
3654
+ this.listenTo(this.regionManager, "region:add", function(name, region){
3655
+ this[name] = region;
3656
+ this.trigger("region:add", name, region);
3657
+ });
3658
+
3659
+ this.listenTo(this.regionManager, "region:remove", function(name, region){
3660
+ delete this[name];
3661
+ this.trigger("region:remove", name, region);
3662
+ });
3663
+ }
3664
+ });
3665
+
3666
+
3667
+ // AppRouter
3668
+ // ---------
3669
+
3670
+ // Reduce the boilerplate code of handling route events
3671
+ // and then calling a single method on another object.
3672
+ // Have your routers configured to call the method on
3673
+ // your object, directly.
3674
+ //
3675
+ // Configure an AppRouter with `appRoutes`.
3676
+ //
3677
+ // App routers can only take one `controller` object.
3678
+ // It is recommended that you divide your controller
3679
+ // objects in to smaller pieces of related functionality
3680
+ // and have multiple routers / controllers, instead of
3681
+ // just one giant router and controller.
3682
+ //
3683
+ // You can also add standard routes to an AppRouter.
3684
+
3685
+ Marionette.AppRouter = Backbone.Router.extend({
3686
+
3687
+ constructor: function(options){
3688
+ Backbone.Router.prototype.constructor.apply(this, slice(arguments));
3689
+
3690
+ this.options = options || {};
3691
+
3692
+ var appRoutes = Marionette.getOption(this, "appRoutes");
3693
+ var controller = this._getController();
3694
+ this.processAppRoutes(controller, appRoutes);
3695
+ },
3696
+
3697
+ // Similar to route method on a Backbone Router but
3698
+ // method is called on the controller
3699
+ appRoute: function(route, methodName) {
3700
+ var controller = this._getController();
3701
+ this._addAppRoute(controller, route, methodName);
3702
+ },
3703
+
3704
+ // Internal method to process the `appRoutes` for the
3705
+ // router, and turn them in to routes that trigger the
3706
+ // specified method on the specified `controller`.
3707
+ processAppRoutes: function(controller, appRoutes) {
3708
+ if (!appRoutes){ return; }
3709
+
3710
+ var routeNames = _.keys(appRoutes).reverse(); // Backbone requires reverted order of routes
3711
+
3712
+ _.each(routeNames, function(route) {
3713
+ this._addAppRoute(controller, route, appRoutes[route]);
3714
+ }, this);
3715
+ },
3716
+
3717
+ _getController: function(){
3718
+ return Marionette.getOption(this, "controller");
3719
+ },
3720
+
3721
+ _addAppRoute: function(controller, route, methodName){
3722
+ var method = controller[methodName];
3723
+
3724
+ if (!method) {
3725
+ throw new Error("Method '" + methodName + "' was not found on the controller");
3726
+ }
3727
+
3728
+ this.route(route, methodName, _.bind(method, controller));
3729
+ }
3730
+ });
3731
+
3732
+
3733
+ // Application
3734
+ // -----------
3735
+
3736
+ // Contain and manage the composite application as a whole.
3737
+ // Stores and starts up `Region` objects, includes an
3738
+ // event aggregator as `app.vent`
3739
+ Marionette.Application = function(options){
3740
+ this._initRegionManager();
3741
+ this._initCallbacks = new Marionette.Callbacks();
3742
+ this.vent = new Backbone.Wreqr.EventAggregator();
3743
+ this.commands = new Backbone.Wreqr.Commands();
3744
+ this.reqres = new Backbone.Wreqr.RequestResponse();
3745
+ this.submodules = {};
3746
+
3747
+ _.extend(this, options);
3748
+
3749
+ this.triggerMethod = Marionette.triggerMethod;
3750
+ };
3751
+
3752
+ _.extend(Marionette.Application.prototype, Backbone.Events, {
3753
+ // Command execution, facilitated by Backbone.Wreqr.Commands
3754
+ execute: function(){
3755
+ var args = Array.prototype.slice.apply(arguments);
3756
+ this.commands.execute.apply(this.commands, args);
3757
+ },
3758
+
3759
+ // Request/response, facilitated by Backbone.Wreqr.RequestResponse
3760
+ request: function(){
3761
+ var args = Array.prototype.slice.apply(arguments);
3762
+ return this.reqres.request.apply(this.reqres, args);
3763
+ },
3764
+
3765
+ // Add an initializer that is either run at when the `start`
3766
+ // method is called, or run immediately if added after `start`
3767
+ // has already been called.
3768
+ addInitializer: function(initializer){
3769
+ this._initCallbacks.add(initializer);
3770
+ },
3771
+
3772
+ // kick off all of the application's processes.
3773
+ // initializes all of the regions that have been added
3774
+ // to the app, and runs all of the initializer functions
3775
+ start: function(options){
3776
+ this.triggerMethod("initialize:before", options);
3777
+ this._initCallbacks.run(options, this);
3778
+ this.triggerMethod("initialize:after", options);
3779
+
3780
+ this.triggerMethod("start", options);
3781
+ },
3782
+
3783
+ // Add regions to your app.
3784
+ // Accepts a hash of named strings or Region objects
3785
+ // addRegions({something: "#someRegion"})
3786
+ // addRegions({something: Region.extend({el: "#someRegion"}) });
3787
+ addRegions: function(regions){
3788
+ return this._regionManager.addRegions(regions);
3789
+ },
3790
+
3791
+ // Close all regions in the app, without removing them
3792
+ closeRegions: function(){
3793
+ this._regionManager.closeRegions();
3794
+ },
3795
+
3796
+ // Removes a region from your app, by name
3797
+ // Accepts the regions name
3798
+ // removeRegion('myRegion')
3799
+ removeRegion: function(region) {
3800
+ this._regionManager.removeRegion(region);
3801
+ },
3802
+
3803
+ // Provides alternative access to regions
3804
+ // Accepts the region name
3805
+ // getRegion('main')
3806
+ getRegion: function(region) {
3807
+ return this._regionManager.get(region);
3808
+ },
3809
+
3810
+ // Create a module, attached to the application
3811
+ module: function(moduleNames, moduleDefinition){
3812
+ // slice the args, and add this application object as the
3813
+ // first argument of the array
3814
+ var args = slice(arguments);
3815
+ args.unshift(this);
3816
+
3817
+ // see the Marionette.Module object for more information
3818
+ return Marionette.Module.create.apply(Marionette.Module, args);
3819
+ },
3820
+
3821
+ // Internal method to set up the region manager
3822
+ _initRegionManager: function(){
3823
+ this._regionManager = new Marionette.RegionManager();
3824
+
3825
+ this.listenTo(this._regionManager, "region:add", function(name, region){
3826
+ this[name] = region;
3827
+ });
3828
+
3829
+ this.listenTo(this._regionManager, "region:remove", function(name, region){
3830
+ delete this[name];
3831
+ });
3832
+ }
3833
+ });
3834
+
3835
+ // Copy the `extend` function used by Backbone's classes
3836
+ Marionette.Application.extend = Marionette.extend;
3837
+
3838
+ // Module
3839
+ // ------
3840
+
3841
+ // A simple module system, used to create privacy and encapsulation in
3842
+ // Marionette applications
3843
+ Marionette.Module = function(moduleName, app){
3844
+ this.moduleName = moduleName;
3845
+
3846
+ // store sub-modules
3847
+ this.submodules = {};
3848
+
3849
+ this._setupInitializersAndFinalizers();
3850
+
3851
+ // store the configuration for this module
3852
+ this.app = app;
3853
+ this.startWithParent = true;
3854
+
3855
+ this.triggerMethod = Marionette.triggerMethod;
3856
+ };
3857
+
3858
+ // Extend the Module prototype with events / listenTo, so that the module
3859
+ // can be used as an event aggregator or pub/sub.
3860
+ _.extend(Marionette.Module.prototype, Backbone.Events, {
3861
+
3862
+ // Initializer for a specific module. Initializers are run when the
3863
+ // module's `start` method is called.
3864
+ addInitializer: function(callback){
3865
+ this._initializerCallbacks.add(callback);
3866
+ },
3867
+
3868
+ // Finalizers are run when a module is stopped. They are used to teardown
3869
+ // and finalize any variables, references, events and other code that the
3870
+ // module had set up.
3871
+ addFinalizer: function(callback){
3872
+ this._finalizerCallbacks.add(callback);
3873
+ },
3874
+
3875
+ // Start the module, and run all of its initializers
3876
+ start: function(options){
3877
+ // Prevent re-starting a module that is already started
3878
+ if (this._isInitialized){ return; }
3879
+
3880
+ // start the sub-modules (depth-first hierarchy)
3881
+ _.each(this.submodules, function(mod){
3882
+ // check to see if we should start the sub-module with this parent
3883
+ if (mod.startWithParent){
3884
+ mod.start(options);
3885
+ }
3886
+ });
3887
+
3888
+ // run the callbacks to "start" the current module
3889
+ this.triggerMethod("before:start", options);
3890
+
3891
+ this._initializerCallbacks.run(options, this);
3892
+ this._isInitialized = true;
3893
+
3894
+ this.triggerMethod("start", options);
3895
+ },
3896
+
3897
+ // Stop this module by running its finalizers and then stop all of
3898
+ // the sub-modules for this module
3899
+ stop: function(){
3900
+ // if we are not initialized, don't bother finalizing
3901
+ if (!this._isInitialized){ return; }
3902
+ this._isInitialized = false;
3903
+
3904
+ Marionette.triggerMethod.call(this, "before:stop");
3905
+
3906
+ // stop the sub-modules; depth-first, to make sure the
3907
+ // sub-modules are stopped / finalized before parents
3908
+ _.each(this.submodules, function(mod){ mod.stop(); });
3909
+
3910
+ // run the finalizers
3911
+ this._finalizerCallbacks.run(undefined,this);
3912
+
3913
+ // reset the initializers and finalizers
3914
+ this._initializerCallbacks.reset();
3915
+ this._finalizerCallbacks.reset();
3916
+
3917
+ Marionette.triggerMethod.call(this, "stop");
3918
+ },
3919
+
3920
+ // Configure the module with a definition function and any custom args
3921
+ // that are to be passed in to the definition function
3922
+ addDefinition: function(moduleDefinition, customArgs){
3923
+ this._runModuleDefinition(moduleDefinition, customArgs);
3924
+ },
3925
+
3926
+ // Internal method: run the module definition function with the correct
3927
+ // arguments
3928
+ _runModuleDefinition: function(definition, customArgs){
3929
+ if (!definition){ return; }
3930
+
3931
+ // build the correct list of arguments for the module definition
3932
+ var args = _.flatten([
3933
+ this,
3934
+ this.app,
3935
+ Backbone,
3936
+ Marionette,
3937
+ Marionette.$, _,
3938
+ customArgs
3939
+ ]);
3940
+
3941
+ definition.apply(this, args);
3942
+ },
3943
+
3944
+ // Internal method: set up new copies of initializers and finalizers.
3945
+ // Calling this method will wipe out all existing initializers and
3946
+ // finalizers.
3947
+ _setupInitializersAndFinalizers: function(){
3948
+ this._initializerCallbacks = new Marionette.Callbacks();
3949
+ this._finalizerCallbacks = new Marionette.Callbacks();
3950
+ }
3951
+ });
3952
+
3953
+ // Type methods to create modules
3954
+ _.extend(Marionette.Module, {
3955
+
3956
+ // Create a module, hanging off the app parameter as the parent object.
3957
+ create: function(app, moduleNames, moduleDefinition){
3958
+ var module = app;
3959
+
3960
+ // get the custom args passed in after the module definition and
3961
+ // get rid of the module name and definition function
3962
+ var customArgs = slice(arguments);
3963
+ customArgs.splice(0, 3);
3964
+
3965
+ // split the module names and get the length
3966
+ moduleNames = moduleNames.split(".");
3967
+ var length = moduleNames.length;
3968
+
3969
+ // store the module definition for the last module in the chain
3970
+ var moduleDefinitions = [];
3971
+ moduleDefinitions[length-1] = moduleDefinition;
3972
+
3973
+ // Loop through all the parts of the module definition
3974
+ _.each(moduleNames, function(moduleName, i){
3975
+ var parentModule = module;
3976
+ module = this._getModule(parentModule, moduleName, app);
3977
+ this._addModuleDefinition(parentModule, module, moduleDefinitions[i], customArgs);
3978
+ }, this);
3979
+
3980
+ // Return the last module in the definition chain
3981
+ return module;
3982
+ },
3983
+
3984
+ _getModule: function(parentModule, moduleName, app, def, args){
3985
+ // Get an existing module of this name if we have one
3986
+ var module = parentModule[moduleName];
3987
+
3988
+ if (!module){
3989
+ // Create a new module if we don't have one
3990
+ module = new Marionette.Module(moduleName, app);
3991
+ parentModule[moduleName] = module;
3992
+ // store the module on the parent
3993
+ parentModule.submodules[moduleName] = module;
3994
+ }
3995
+
3996
+ return module;
3997
+ },
3998
+
3999
+ _addModuleDefinition: function(parentModule, module, def, args){
4000
+ var fn;
4001
+ var startWithParent;
4002
+
4003
+ if (_.isFunction(def)){
4004
+ // if a function is supplied for the module definition
4005
+ fn = def;
4006
+ startWithParent = true;
4007
+
4008
+ } else if (_.isObject(def)){
4009
+ // if an object is supplied
4010
+ fn = def.define;
4011
+ startWithParent = def.startWithParent;
4012
+
4013
+ } else {
4014
+ // if nothing is supplied
4015
+ startWithParent = true;
4016
+ }
4017
+
4018
+ // add module definition if needed
4019
+ if (fn){
4020
+ module.addDefinition(fn, args);
4021
+ }
4022
+
4023
+ // `and` the two together, ensuring a single `false` will prevent it
4024
+ // from starting with the parent
4025
+ module.startWithParent = module.startWithParent && startWithParent;
4026
+
4027
+ // setup auto-start if needed
4028
+ if (module.startWithParent && !module.startWithParentIsConfigured){
4029
+
4030
+ // only configure this once
4031
+ module.startWithParentIsConfigured = true;
4032
+
4033
+ // add the module initializer config
4034
+ parentModule.addInitializer(function(options){
4035
+ if (module.startWithParent){
4036
+ module.start(options);
4037
+ }
4038
+ });
4039
+
4040
+ }
4041
+
4042
+ }
4043
+ });
4044
+
4045
+
4046
+
4047
+ return Marionette;
4048
+ })(this, Backbone, _);
4049
+
4050
+ /*!
4051
+ * Tableling v0.0.22
4052
+ * Copyright (c) 2012-2013 Simon Oulevay (Alpha Hydrae) <hydrae.alpha@gmail.com>
4053
+ * Distributed under MIT license
4054
+ * https://github.com/AlphaHydrae/tableling
4055
+ */
4056
+ Backbone.Tableling = Tableling = (function(Backbone, _, $){
4057
+
4058
+ var Tableling = {
4059
+ version : "0.0.22"
4060
+ };
4061
+
4062
+ // Tableling
4063
+ // ---------
4064
+ //
4065
+ // A tableling table is a Marionette layout which fetches data
4066
+ // from a Backbone collection. It is controlled with an EventAggregator.
4067
+ Tableling.Table = Backbone.Marionette.Layout.extend({
4068
+
4069
+ className: 'tableling',
4070
+
4071
+ // Default table options can be overriden by subclasses.
4072
+ config : {
4073
+ page : 1
4074
+ },
4075
+
4076
+ initialize : function(options) {
4077
+ options = options || {};
4078
+
4079
+ this.collection = options.collection;
4080
+
4081
+ // Table options can also be overriden for each instance at construction.
4082
+ this.config = _.extend(_.clone(this.config || {}), _.result(options, 'config') || {});
4083
+
4084
+ // We use an event aggregator to manage the layout and its components.
4085
+ // You can use your own by passing a `vent` option.
4086
+ this.vent = options.vent || new Backbone.Wreqr.EventAggregator();
4087
+
4088
+ this.fetchOptions = _.extend(_.clone(this.fetchOptions || {}), _.result(options, 'fetchOptions') || {});
4089
+ this.autoUpdate = typeof(options.autoUpdate) != 'undefined' ? options.autoUpdate : true;
4090
+
4091
+ // Components should trigger the `table:update` event to update
4092
+ // the table (e.g. change page size, sort) and fetch the new data.
4093
+ this.vent.on('table:update', this.onUpdate, this);
4094
+
4095
+ this.on('item:rendered', this.setup, this);
4096
+ },
4097
+
4098
+ // Called once rendering is complete. By default, it updates the table.
4099
+ setup : function() {
4100
+ this.ventTrigger('table:setup', this.config);
4101
+ if (this.autoUpdate) {
4102
+ this.ventTrigger('table:update');
4103
+ }
4104
+ },
4105
+
4106
+ // Subclasses must return the Backbone.Collection used to fetch data.
4107
+ getCollection : function() {
4108
+ return this.collection;
4109
+ },
4110
+
4111
+ // ### Refreshing the table
4112
+ update : function(config, options) {
4113
+ this.ventTrigger('table:update', config, options);
4114
+ },
4115
+
4116
+ onUpdate : function(config, options) {
4117
+
4118
+ _.each(config || {}, _.bind(this.updateValue, this));
4119
+
4120
+ // Set the `refresh` option to false to update the table configuration
4121
+ // without refreshing.
4122
+ if (!options || typeof(options.refresh) == 'undefined' || options.refresh) {
4123
+ this.refresh();
4124
+ }
4125
+ },
4126
+
4127
+ updateValue : function(value, key) {
4128
+ if (value && value.toString().length) {
4129
+ this.config[key] = value;
4130
+ } else {
4131
+ // Blank values are deleted to avoid sending them in ajax requests.
4132
+ delete this.config[key];
4133
+ }
4134
+ },
4135
+
4136
+ refresh : function() {
4137
+
4138
+ // You can provide `fetchOptions` to add properties to the
4139
+ // fetch request.
4140
+ //
4141
+ // var MyTable = Tableling.Table.extend({
4142
+ // fetchOptions : {
4143
+ // type : 'POST' // fetch data with POST
4144
+ // }
4145
+ // });
4146
+ //
4147
+ // // You can also override for each instance.
4148
+ // new MyTable({
4149
+ // fetchOptions : {
4150
+ // type : 'GET'
4151
+ // }
4152
+ // });
4153
+ var options = _.clone(this.fetchOptions);
4154
+ options.data = this.requestData();
4155
+ options.success = _.bind(this.processResponse, this);
4156
+
4157
+ // `table:refreshing` is triggered every time new data is being fetched.
4158
+ // The first argument is the request data.
4159
+ this.ventTrigger('table:refreshing', options.data);
4160
+
4161
+ this.getCollection().fetch(options);
4162
+ },
4163
+
4164
+ // ### Request
4165
+ requestData : function() {
4166
+ return this.config;
4167
+ },
4168
+
4169
+ // ### Response
4170
+ processResponse : function(collection, response) {
4171
+
4172
+ this.config.length = collection.length;
4173
+
4174
+ // Tableling expects the response from a fetch to have a `total` property
4175
+ // which is the total number of items (not just in the current page).
4176
+ this.config.total = response.total;
4177
+
4178
+ // The server may override the `page` property, for example if the
4179
+ // requested page was outside the range of available pages.
4180
+ if (response.page) {
4181
+ this.config.page = response.page;
4182
+ }
4183
+
4184
+ // `tableling:refreshed` is triggered after every refresh. The first argument
4185
+ // is the current table configuration with the following additional meta data:
4186
+ //
4187
+ // * `total` - the total number of items
4188
+ // * `length` - the number of items in the current page
4189
+ this.ventTrigger('table:refreshed', this.config);
4190
+ },
4191
+
4192
+ // Triggers an event in the event aggregator. If `Tableling.debug` is set, it also
4193
+ // logs the event and its arguments.
4194
+ ventTrigger : function() {
4195
+
4196
+ var args = Array.prototype.slice.call(arguments);
4197
+ if (Tableling.debug) {
4198
+ console.log(_.first(args) + ' - ' + JSON.stringify(args.slice(1)));
4199
+ }
4200
+
4201
+ this.vent.trigger.apply(this.vent, args);
4202
+ }
4203
+ });
4204
+
4205
+ // Tableling.Collection
4206
+ // --------------------
4207
+ //
4208
+ // Tableling expects fetch responses to have a `total` property in addition
4209
+ // to the model data. You can extend this Backbone.Collection subclass which
4210
+ // expects the following response format:
4211
+ //
4212
+ // {
4213
+ // "total": 12,
4214
+ // "data": [
4215
+ // { /* ... model data ... */ },
4216
+ // { /* ... model data ... */ }
4217
+ // ]
4218
+ // }
4219
+ Tableling.Collection = Backbone.Collection.extend({
4220
+
4221
+ parse : function(response) {
4222
+ return response.data;
4223
+ }
4224
+ });
4225
+
4226
+ // Implementations
4227
+ // ---------------
4228
+ //
4229
+ // <a href="tableling.bootstrap.html">tableling.bootstrap</a> provides views styled
4230
+ // with [Twitter Bootstrap](http://twitter.github.com/bootstrap/) classes.
4231
+
4232
+ // Tableling.Modular
4233
+ // -----------------
4234
+ //
4235
+ // Tableling subclass which splits functionality into *modules*
4236
+ // and handles rendering.
4237
+ Tableling.Modular = Tableling.Table.extend({
4238
+
4239
+ // The list of module names must be specified by subclasses.
4240
+ modules : [],
4241
+
4242
+ // Modules are set up after rendering, before refreshing.
4243
+ setup : function() {
4244
+
4245
+ this.moduleViews = {};
4246
+ _.each(this.modules, _.bind(this.setupModule, this));
4247
+
4248
+ Tableling.Table.prototype.setup.call(this);
4249
+ },
4250
+
4251
+ // ### Modules
4252
+ // Each module is identified by a name, for example `pageSize`.
4253
+ setupModule : function(name) {
4254
+
4255
+ // The layout must have a region named after the module, e.g. `pageSizeRegion`.
4256
+ var region = name + 'Region';
4257
+
4258
+ // It must have a view class, e.g. `pageSizeView`, which will be shown into
4259
+ // the region.
4260
+ var viewClass = this[name + 'View'];
4261
+
4262
+ // When instantiated, the view class will be passed the event
4263
+ // aggregator as the `vent` option. Additional options can be
4264
+ // given named after the view class, e.g. `pageSizeViewOptions`.
4265
+ var options = _.extend(this.getModuleOptions(name), { vent: this.vent });
4266
+
4267
+ var view = new viewClass(options);
4268
+
4269
+ // Module view instances are stored by name in the `moduleViews` property
4270
+ // for future reference.
4271
+ this.moduleViews[name] = view;
4272
+
4273
+ this[region].show(view);
4274
+ return view;
4275
+ },
4276
+
4277
+ // By default the collection is the one given at construction.
4278
+ // Otherwise, a modular table expects a `table` module which
4279
+ // should have a collection (e.g. a Marionette CompositeView or
4280
+ // CollectionView). If your subclass does not have either, it
4281
+ // should override this method to return the Backbone.Collection
4282
+ // used to fetch table data.
4283
+ getCollection : function() {
4284
+ return this.collection || (this.moduleViews && this.moduleViews.table ? this.moduleViews.table.collection : undefined);
4285
+ },
4286
+
4287
+ getModuleOptions : function(name) {
4288
+ var options = this[name + 'ViewOptions'] || {};
4289
+ options = typeof(options) == 'function' ? options.call(this) : options;
4290
+ return name == 'table' ? _.defaults(options, { collection : this.collection }) : options;
4291
+ }
4292
+ });
4293
+
4294
+ // ### Example
4295
+ // This is how a `PageSizeView` module might be registered in a subclass:
4296
+ //
4297
+ // var MyTable = Tableling.Modular.extend({
4298
+ //
4299
+ // modules : [ 'pageSize' ],
4300
+ //
4301
+ // pageSizeView : PageSizeView,
4302
+ // pageSizeViewOptions : {
4303
+ // itemView : PageSizeItem
4304
+ // },
4305
+ //
4306
+ // regions : {
4307
+ // pageSizeRegion : '.pageSize'
4308
+ // }
4309
+ // });
4310
+
4311
+ // Tableling.Module
4312
+ // ----------------
4313
+ //
4314
+ // A module is an item view that is automatically bound to the table's
4315
+ // event aggregator.
4316
+ Tableling.Module = Backbone.Marionette.ItemView.extend({
4317
+
4318
+ i18n : {},
4319
+ templateHelpers : function() {
4320
+ return this.i18n;
4321
+ },
4322
+
4323
+ initialize : function(options) {
4324
+
4325
+ this.vent = options.vent;
4326
+
4327
+ // The `setup` method of the view is called when the table
4328
+ // is first set up.
4329
+ this.vent.on('table:setup', this.setup, this);
4330
+
4331
+ // The `refresh` method of the view is called every time the table
4332
+ // is refreshed.
4333
+ this.vent.on('table:refreshed', this.refresh, this);
4334
+
4335
+ this.i18n = _.clone(options.i18n || this.i18n);
4336
+ },
4337
+
4338
+ // Call `update` to trigger an update of the table.
4339
+ update : function() {
4340
+ this.vent.trigger('table:update', this.config());
4341
+ },
4342
+
4343
+ // Implementations should override this to set initial values.
4344
+ setup : function(config) {
4345
+ },
4346
+
4347
+ // Implementations should override this to stay up to date with
4348
+ // the table state.
4349
+ refresh : function(config) {
4350
+ },
4351
+
4352
+ // New table configuration to be sent on updates. For example,
4353
+ // a page size view might update the `pageSize` property.
4354
+ config : function() {
4355
+ return {};
4356
+ }
4357
+ });
4358
+
4359
+ // Tableling.FieldModule
4360
+ // ---------------------
4361
+ //
4362
+ // A basic module with a single form field. It comes with sensible
4363
+ // defaults and only requires a `name` and a `template` parameter.
4364
+ Tableling.FieldModule = Tableling.Module.extend({
4365
+
4366
+ // TODO: check name
4367
+
4368
+ initialize : function(options) {
4369
+
4370
+ Tableling.Module.prototype.initialize.call(this, options);
4371
+
4372
+ if (!this.ui) {
4373
+ this.ui = {};
4374
+ }
4375
+ // The name attribute of the form field is the same as the
4376
+ // module's, e.g. `pageSize`.
4377
+ this.ui.field = '[name="' + this.name + '"]';
4378
+
4379
+ if (!this.events) {
4380
+ this.events = {};
4381
+ }
4382
+ this.events['change [name="' + this.name + '"]'] = 'update';
4383
+ },
4384
+
4385
+ setup : function(config) {
4386
+ this.setupValue(config[this.name]);
4387
+ this.vent.trigger('table:update', this.config(), { refresh : false });
4388
+ },
4389
+
4390
+ setupValue : function(value) {
4391
+ this.ui.field.val(value);
4392
+ },
4393
+
4394
+ // The table property updated is the one with the same name as the module.
4395
+ config : function() {
4396
+ var config = {};
4397
+ config[this.name] = this.ui.field.val();
4398
+ return config;
4399
+ }
4400
+ });
4401
+
4402
+ // This is how a `PageSizeView` module might be implemented:
4403
+ //
4404
+ // var html = '<input type="text" name="pageSize" />';
4405
+ //
4406
+ // var PageSizeView = Tableling.FieldModule.extend({
4407
+ // name : 'pageSize'
4408
+ // template : _.template(html)
4409
+ // });
4410
+ //
4411
+ // When the value of the input field changes, the event aggregator will
4412
+ // receive a `tableling:update` event with the `pageSize` property set
4413
+ // to that value.
4414
+
4415
+ Tableling.Plain = {};
4416
+
4417
+ Tableling.Plain.Table = Tableling.Modular.extend({
4418
+
4419
+ className: 'tableling',
4420
+ modules : [ 'table', 'pageSize', 'quickSearch', 'info', 'page' ],
4421
+ template : _.template('<div class="header"><div class="pageSize" /><div class="quickSearch" /></div><div class="table" /><div class="footer"><div class="info" /><div class="page" /></div>'),
4422
+
4423
+ regions : {
4424
+ tableRegion : '.table',
4425
+ pageSizeRegion : '.pageSize',
4426
+ quickSearchRegion : '.quickSearch',
4427
+ infoRegion : '.info',
4428
+ pageRegion : '.page'
4429
+ }
4430
+ });
4431
+
4432
+ Tableling.Plain.TableView = Backbone.Marionette.CompositeView.extend({
4433
+
4434
+ events : {
4435
+ 'click thead th.sorting' : 'updateSort',
4436
+ 'click thead th.sorting-asc' : 'updateSort',
4437
+ 'click thead th.sorting-desc' : 'updateSort'
4438
+ },
4439
+
4440
+ initialize : function(options) {
4441
+ // TODO: add auto-sort
4442
+ this.vent = options.vent;
4443
+ this.sort = [];
4444
+ this.vent.on('table:setup', this.setSort, this);
4445
+ this.vent.on('table:refreshed', this.setSort, this);
4446
+ },
4447
+
4448
+ updateSort : function(ev) {
4449
+
4450
+ var el = $(ev.currentTarget);
4451
+ if (!(el.hasClass('sorting') || el.hasClass('sorting-asc') || el.hasClass('sorting-desc'))) {
4452
+ return;
4453
+ }
4454
+
4455
+ var field = this.fieldName(el);
4456
+
4457
+ if (ev.shiftKey || this.sort.length == 1) {
4458
+
4459
+ var index = -1;
4460
+ _.find(this.sort, function(item, i) {
4461
+ if (item.split(' ')[0] == field) {
4462
+ index = i;
4463
+ }
4464
+ });
4465
+
4466
+ if (index >= 0) {
4467
+
4468
+ var parts = this.sort[index].split(' ');
4469
+ this.sort[index] = parts[0] + ' ' + (parts[1] == 'asc' ? 'desc' : 'asc');
4470
+ this.showSort();
4471
+ return this.vent.trigger('table:update', this.config());
4472
+ }
4473
+ }
4474
+
4475
+ if (!ev.shiftKey) {
4476
+ this.sort.length = 0;
4477
+ }
4478
+
4479
+ this.sort.push(field + ' asc');
4480
+
4481
+ this.showSort();
4482
+
4483
+ this.vent.trigger('table:update', this.config());
4484
+ },
4485
+
4486
+ setSort : function(config) {
4487
+ if (config && config.sort) {
4488
+ this.sort = config.sort.slice(0);
4489
+ this.showSort();
4490
+ }
4491
+ },
4492
+
4493
+ showSort : function() {
4494
+
4495
+ this.$el.find('thead th.sorting, thead th.sorting-asc, thead th.sorting-desc').removeClass('sorting sorting-asc sorting-desc').addClass('sorting');
4496
+
4497
+ for (var i = 0; i < this.sort.length; i++) {
4498
+
4499
+ var parts = this.sort[i].split(' ');
4500
+ var name = parts[0];
4501
+ var direction = parts[1];
4502
+
4503
+ field = this.$el.find('thead [data-field="' + name + '"]');
4504
+ if (!field.length) {
4505
+ field = this.$el.find('thead th:contains("' + name + '")');
4506
+ }
4507
+
4508
+ if (field.length) {
4509
+ field.removeClass('sorting').addClass(direction == 'desc' ? 'sorting-desc' : 'sorting-asc');
4510
+ }
4511
+ }
4512
+ },
4513
+
4514
+ config : function() {
4515
+ return {
4516
+ page : 1,
4517
+ sort : this.sortConfig()
4518
+ };
4519
+ },
4520
+
4521
+ sortConfig : function() {
4522
+ return this.sort.length ? this.sort : null;
4523
+ },
4524
+
4525
+ fieldName : function(el) {
4526
+ return el.data('field') || el.text();
4527
+ }
4528
+ });
4529
+
4530
+ Tableling.Plain.PageSizeView = Tableling.Plain.Table.prototype.pageSizeView = Tableling.FieldModule.extend({
4531
+
4532
+ // TODO: update current page intelligently
4533
+ name : 'pageSize',
4534
+ template : function(data) {
4535
+ return _.template('<select name="pageSize" /> <%- entries %>', data);
4536
+ },
4537
+
4538
+ i18n : {
4539
+ entries : 'entries per page'
4540
+ },
4541
+ sizes : [ 10, 15, 20, 25, 50 ],
4542
+
4543
+ ui : {
4544
+ field : 'select'
4545
+ },
4546
+
4547
+ initialize : function(options) {
4548
+ Tableling.FieldModule.prototype.initialize.call(this, options);
4549
+ this.sizes = _.clone(options.sizes || this.sizes);
4550
+ },
4551
+
4552
+ onRender : function() {
4553
+ this.ui.field.empty();
4554
+ _.each(this.sizes, _.bind(this.addSize, this));
4555
+ },
4556
+
4557
+ addSize : function(size) {
4558
+ $('<option />').text(size).appendTo(this.ui.field);
4559
+ },
4560
+
4561
+ setupValue : function(value) {
4562
+ if (value) {
4563
+ Tableling.FieldModule.prototype.setupValue.apply(this, Array.prototype.slice.call(arguments));
4564
+ }
4565
+ },
4566
+
4567
+ config : function() {
4568
+ var config = Tableling.FieldModule.prototype.config.call(this);
4569
+ config.page = 1;
4570
+ return config;
4571
+ }
4572
+ });
4573
+
4574
+ Tableling.Plain.QuickSearchView = Tableling.Plain.Table.prototype.quickSearchView = Tableling.FieldModule.extend({
4575
+
4576
+ name : 'quickSearch',
4577
+ template : function(data) {
4578
+ return _.template('<input type="text" name="quickSearch" placeholder="<%- quickSearch %>" />', data);
4579
+ },
4580
+
4581
+ i18n : {
4582
+ quickSearch : 'Quick search...'
4583
+ },
4584
+
4585
+ config : function() {
4586
+ var config = Tableling.FieldModule.prototype.config.call(this);
4587
+ config.page = 1;
4588
+ return config;
4589
+ }
4590
+ });
4591
+
4592
+ Tableling.Plain.InfoView = Tableling.Plain.Table.prototype.infoView = Tableling.Module.extend({
4593
+
4594
+ template : function(data) {
4595
+ return _.template(data.template, {
4596
+ first : '<span class="first">0</span>',
4597
+ last : '<span class="last">0</span>',
4598
+ total : '<span class="total">0</span>'
4599
+ });
4600
+ },
4601
+
4602
+ i18n : {
4603
+ template : 'Showing <%= first %> to <%= last %> of <%= total %> entries'
4604
+ },
4605
+
4606
+ ui : {
4607
+ first: '.first',
4608
+ last: '.last',
4609
+ total: '.total'
4610
+ },
4611
+
4612
+ refresh : function(data) {
4613
+ if (data) {
4614
+ this.ui.first.text(this.firstRecord(data));
4615
+ this.ui.last.text(this.lastRecord(data));
4616
+ this.ui.total.text(data.total);
4617
+ }
4618
+ },
4619
+
4620
+ firstRecord : function(data) {
4621
+ return data.length ? ((data.page || 1) - 1) * data.pageSize + 1 : 0;
4622
+ },
4623
+
4624
+ lastRecord : function(data) {
4625
+ return data.length ? this.firstRecord(data) + data.length - 1 : 0;
4626
+ }
4627
+ });
4628
+
4629
+ Tableling.Plain.PageView = Tableling.Plain.Table.prototype.pageView = Tableling.Module.extend({
4630
+
4631
+ template : _.template('<div class="pagination"><ul><li class="first"><a href="#">&lt;&lt;</a></li><li class="previous"><a href="#">&lt;</a></li><li class="next"><a href="#">&gt;</a></li><li class="last"><a href="#">&gt;&gt;</a></li></ul></div>'),
4632
+ pageTemplate : _.template('<li class="page"><a href="#"><%- number %></a></li>'),
4633
+
4634
+ ui : {
4635
+ first : '.first',
4636
+ previous : '.previous',
4637
+ next : '.next',
4638
+ last : '.last'
4639
+ },
4640
+
4641
+ events : {
4642
+ 'click .first:not(.disabled)' : 'goToFirstPage',
4643
+ 'click .previous:not(.disabled)' : 'goToPreviousPage',
4644
+ 'click .page:not(.disabled)' : 'goToPage',
4645
+ 'click .next:not(.disabled)' : 'goToNextPage',
4646
+ 'click .last:not(.disabled)' : 'goToLastPage'
4647
+ },
4648
+
4649
+ refresh : function(data) {
4650
+ this.$el.find('.page').remove();
4651
+ if (!data || !data.length) {
4652
+ this.ui.first.addClass('disabled');
4653
+ this.ui.previous.addClass('disabled');
4654
+ this.ui.next.addClass('disabled');
4655
+ this.ui.last.addClass('disabled');
4656
+ } else {
4657
+ this.data = data;
4658
+ this.enable(this.ui.first, this.getPage(data) > 1);
4659
+ this.enable(this.ui.previous, this.getPage(data) > 1);
4660
+ this.setupPages();
4661
+ this.enable(this.ui.next, this.getPage(data) < this.numberOfPages(data));
4662
+ this.enable(this.ui.last, this.getPage(data) < this.numberOfPages(data));
4663
+ }
4664
+ },
4665
+
4666
+ setupPages : function() {
4667
+
4668
+ var page = this.getPage(this.data);
4669
+ var total = this.numberOfPages();
4670
+
4671
+ var first = page - 2;
4672
+ if (total - first < 4) {
4673
+ first = total - 4;
4674
+ }
4675
+
4676
+ if (first < 1) {
4677
+ first = 1;
4678
+ }
4679
+
4680
+ var n = 5;
4681
+ if (first + n - 1 > total) {
4682
+ n = total - first + 1;
4683
+ }
4684
+
4685
+ _.times(n, function(i) {
4686
+ $(this.pageTemplate({ number : first + i })).insertBefore(this.ui.next);
4687
+ }, this);
4688
+
4689
+ var i = page - first;
4690
+ this.$el.find('.page').slice(i, i + 1).addClass('disabled');
4691
+ },
4692
+
4693
+ enable : function(el, enabled) {
4694
+ el.removeClass('disabled');
4695
+ if (!enabled) {
4696
+ el.addClass('disabled');
4697
+ }
4698
+ },
4699
+
4700
+ numberOfPages : function() {
4701
+ return Math.ceil(this.data.total / this.data.pageSize);
4702
+ },
4703
+
4704
+ goToFirstPage : function(e) {
4705
+ e.preventDefault();
4706
+ this.goToPageNumber(1);
4707
+ },
4708
+
4709
+ goToPreviousPage : function(e) {
4710
+ e.preventDefault();
4711
+ this.goToPageNumber(this.getPage(this.data) - 1);
4712
+ },
4713
+
4714
+ goToPage : function(e) {
4715
+ e.preventDefault();
4716
+ this.goToPageNumber(parseInt($(e.target).text(), 10));
4717
+ },
4718
+
4719
+ goToNextPage : function(e) {
4720
+ e.preventDefault();
4721
+ this.goToPageNumber(this.getPage(this.data) + 1);
4722
+ },
4723
+
4724
+ goToLastPage : function(e) {
4725
+ e.preventDefault();
4726
+ this.goToPageNumber(this.numberOfPages());
4727
+ },
4728
+
4729
+ goToPageNumber : function(n) {
4730
+ this.vent.trigger('table:update', { page : n });
4731
+ },
4732
+
4733
+ getPage : function(data) {
4734
+ return data.page || 1;
4735
+ }
4736
+ });
4737
+
4738
+ Tableling.Bootstrap = {};
4739
+
4740
+ Tableling.Bootstrap.Table = Tableling.Plain.Table.extend({
4741
+ template : _.template('<div class="header"><div class="pageSize pull-left" /><div class="quickSearch pull-right" /></div><div class="table" /><div class="footer"><div class="info pull-left" /><div class="page pull-right" /></div>')
4742
+ });
4743
+
4744
+ Tableling.Bootstrap.TableView = Tableling.Plain.TableView.extend({});
4745
+
4746
+ Tableling.Bootstrap.PageSizeView = Tableling.Bootstrap.Table.prototype.pageSizeView = Tableling.Plain.PageSizeView.extend({
4747
+
4748
+ template : function(data) {
4749
+ return _.template('<select name="pageSize" class="input-mini"><option>5</option><option>10</option><option>15</option></select> <%- entries %>', data);
4750
+ }
4751
+ });
4752
+
4753
+ Tableling.Bootstrap.QuickSearchView = Tableling.Bootstrap.Table.prototype.quickSearchView = Tableling.Plain.QuickSearchView.extend({});
4754
+
4755
+ Tableling.Bootstrap.InfoView = Tableling.Bootstrap.Table.prototype.infoView = Tableling.Plain.InfoView.extend({});
4756
+
4757
+ Tableling.Bootstrap.PageView = Tableling.Bootstrap.Table.prototype.pageView = Tableling.Plain.PageView.extend({});
4758
+
4759
+
4760
+ return Tableling;
4761
+
4762
+ })(Backbone, _, $ || window.jQuery || window.Zepto || window.ender);