forked from tbranyen/backbone.layoutmanager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackbone.layoutmanager.js
More file actions
633 lines (510 loc) · 19.2 KB
/
backbone.layoutmanager.js
File metadata and controls
633 lines (510 loc) · 19.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
/*!
* backbone.layoutmanager.js v0.5.0
* Copyright 2012, Tim Branyen (@tbranyen)
* backbone.layoutmanager.js may be freely distributed under the MIT license.
*/
(function(window) {
"use strict";
// Alias the libraries from the global object
var Backbone = window.Backbone;
var _ = window._;
var $ = window.$;
var LayoutManager = Backbone.View.extend({
// This is a named function to improve logging and debugging within browser
// dev tools. Typically you do not use "anonymous" named functions since IE
// has a well known bug, BUT I think we all know the reason why I'm ignoring
// that here.
constructor: function LayoutManager(options) {
options = options || {};
// Apply the default render scheme.
this._render = function(manage) {
return manage(this).render();
};
// Ensure the View is setup correctly
LayoutManager.setupView(this, options);
// Set the prefix for a layout
if (options.paths) {
this._prefix = options.paths.layout || "";
}
// Have Backbone set up the rest of this View
Backbone.View.call(this, options);
},
// Shorthand to root.view function with append flag.
insertView: function(partial, view) {
if (view) {
return this.setView(partial, view, true);
}
// Omitting a partial will place the View directly into the parent.
return this.setView(partial, true);
},
// Works like insertView, except allows you to bulk insert via setViews.
insertViews: function(views) {
// Ensure each view is wrapped in an array.
_.each(views, function(view, selector) {
views[selector] = [].concat(view);
});
return this.setViews(views);
},
// Will return a single view that matches the filter function.
getView: function(fn) {
return this.getViews(fn).first().value();
},
// Provide a filter function to get a flattened array of all the subviews.
// If the filter function is omitted it will return all subviews.
getViews: function(fn) {
// Flatten all views.
var views = _.chain(this.views).map(function(view) {
return [].concat(view);
}, this).flatten().value();
// Return a wrapped function to allow for easier chaining.
return _.chain(_.filter(views, fn ? fn : _.identity));
},
// This takes in a partial name and view instance and assigns them to
// the internal collection of views. If a view is not a LayoutManager
// instance, then mix in the LayoutManager prototype. This ensures
// all Views can be used successfully.
//
// Must definitely wrap any render method passed in or defaults to a
// typical render function `return layout(this).render()`.
setView: function(name, view, append) {
var partials, options;
var root = this;
// If no name was passed, use an empty string and shift all arguments.
if (!_.isString(name)) {
append = view;
view = name;
name = "";
}
// If the parent View's object, doesn't exist... create it.
this.views = this.views || {};
// Ensure remove is called when swapping View's.
if (!append && this.views[name]) {
this.views[name].remove();
}
// Instance overrides take precedence, fallback to prototype options.
options = view._options();
// Ensure render is set correctly.
if (options.render !== LayoutManager.prototype.options.render) {
view.render = options.render;
options.render = LayoutManager.prototype.options.render;
}
// Set up the View.
LayoutManager.setupView(view, options);
// Add in all missing LayoutManager properties and methods.
view._render = view.render;
// If no render override was specified assign the default
if (view.render === Backbone.View.prototype.render) {
view._render = function(layout) {
return layout(this).render();
};
}
// Custom template render function.
view.render = function(done) {
var viewDeferred = options.deferred();
// Break this callback out so that its not duplicated inside the
// following safety try/catch.
function renderCallback() {
// Only refresh the view if its not a list item, otherwise it would
// cause duplicates.
if (!view.__manager__.hasRendered) {
// Only if the partial was successful.
if (options.partial(root.el, name, view.el, append)) {
// Set the internal rendered flag, since the View has finished
// rendering.
view.__manager__.hasRendered = true;
}
// Ensure DOM events are properly bound.
view.delegateEvents();
}
// Resolve the View's render handler deferred.
view.__manager__.handler.resolveWith(view, [view.el]);
// When a view has been resolved, ensure that it is correctly updated
// and that any done callbacks are triggered.
viewDeferred.resolveWith(view, [view.el]);
// Only call the done function if a callback was provided.
if (_.isFunction(done)) {
done.call(view, view.el);
}
}
// Call the original render method
LayoutManager.prototype.render.call(view).then(renderCallback);
return viewDeferred.promise();
};
// Append View's get managed inside the render callback.
if (!append) {
view.__manager__.isManaged = true;
}
// Set the prefix for a layout.
if (!view._prefix && options.paths) {
view._prefix = options.paths.template || "";
}
// Special logic for appending items. List items are represented as an
// array.
if (append) {
partials = this.views[name] = this.views[name] || [];
if (!_.isArray(this.views[name])) {
// Ensure this.views[name] is an array.
partials = this.views[name] = [this.views[name]];
}
partials.push(view);
return view;
}
// Assign to main views object and return for chainability.
return this.views[name] = view;
},
// Allows the setting of multiple views instead of a single view.
setViews: function(views) {
// Iterate over all the views and use the View's view method to assign.
_.each(views, function(view, name) {
// If the view is an array put all views into insert mode
if (_.isArray(view)) {
return _.each(view, function(view) {
this.setView(name, view, true);
}, this);
}
// Assign each view using the view function
this.setView(name, view);
}, this);
// Allow for chaining
return this;
},
// By default this should find all nested views and render them into
// the this.el and call done once all of them have successfully been
// resolved.
//
// This function returns a promise that can be chained to determine
// once all subviews and main view have been rendered into the view.el.
render: function(done) {
var root = this;
var options = this._options();
var viewDeferred = options.deferred();
// Only remove views that are in append mode.
this.removeView(true);
// Iterate over all the View's before rendering.
_.each(this.views, function(view, selector) {
// We only care about list items.
if (!_.isArray(view)) {
return;
}
// For every view in the array, remove the View and it's children.
_.each(view, function(view) {
view.remove();
});
// Remove the object from memory.
delete this.views[selector];
}, this);
// Ensure duplicate renders don't override
if (root.__manager__.renderDeferred) {
return root.__manager__.renderDeferred;
}
// Wait until this View has rendered before dealing with nested Views.
this._render(LayoutManager._viewRender).fetch.then(function() {
// Disable the ability for any new sub-views to be added.
root.__manager__.renderDeferred = viewDeferred;
// Create a list of promises to wait on until rendering is done. Since
// this method will run on all children as well, its sufficient for a
// full hierarchical.
var promises = _.map(root.views, function(view) {
// Hoist deferred var, used later on...
var def;
// Ensure views are rendered in sequence
function seqRender(views, done) {
// Once all views have been rendered invoke the sequence render
// callback.
if (!views.length) {
return done();
}
// Get each view in order, grab the first one off the stack.
var view = views.shift();
// This View is now managed by LayoutManager *toot*.
view.__manager__.isManaged = true;
// Render the View and once complete call the next view.
view.render(function() {
// Invoke the recursive sequence render function with the
// remaining views.
seqRender(views, done);
});
}
// If rendering a list out, ensure they happen in a serial order
if (_.isArray(view)) {
// A singular deferred that represents all the items.
def = options.deferred();
seqRender(_.clone(view), function() {
def.resolve();
});
return def.promise();
}
// This View is now managed by LayoutManager *toot*.
view.__manager__.isManaged = true;
// Only return the fetch deferred, resolve the main deferred after
// the element has been attached to it's parent.
return view.render();
});
// Once all subViews have been rendered, resolve this View's deferred.
options.when(promises).then(function() {
viewDeferred.resolveWith(root, [root.el]);
});
});
// Return a promise that resolves once all immediate subViews have
// rendered.
return viewDeferred.then(function() {
// Only call the done function if a callback was provided.
if (_.isFunction(done)) {
done.call(root, root.el);
}
// Remove the rendered deferred
delete root.__manager__.renderDeferred;
}).promise();
},
// Ensure the cleanup function is called whenever remove is called.
remove: function() {
LayoutManager.cleanViews(this);
// Call the original remove function
return this._remove.apply(this, arguments);
},
// Merge instance and global options.
_options: function() {
// Instance overrides take precedence, fallback to prototype options.
return _.extend({}, LayoutManager.prototype.options, this.options);
}
},
{
// Clearable cache
_cache: {},
// Creates a deferred and returns a function to call when finished.
_makeAsync: function(options, done) {
var handler = options.deferred();
// Used to handle asynchronous renders
handler.async = function() {
handler._isAsync = true;
return done;
};
return handler;
},
// This gets passed to all _render methods.
_viewRender: function(root) {
var url, contents, handler;
var options = root._options();
// Once the template is successfully fetched, use its contents to
// proceed. Context argument is first, since it is bound for
// partial application reasons.
function done(context, contents) {
// Ensure the cache is up-to-date.
LayoutManager.cache(url, contents);
// Render the View into the el property.
if (contents) {
options.html(root.el, options.render(contents, context));
}
// Resolve only the fetch (used internally) deferred with the View element.
handler.fetch.resolveWith(root, [root.el]);
}
return {
// This render function is what gets called inside of the View render,
// when manage(this).render is called. Returns a promise that can be
// used to know when the element has been rendered into its parent.
render: function(context) {
var template = root.template || options.template;
if (root.serialize) {
options.serialize = root.serialize;
}
// Seek out serialize method and use that object.
if (!context && _.isFunction(options.serialize)) {
context = options.serialize.call(root);
// If serialize is an object, just use that
} else if (!context && _.isObject(options.serialize)) {
context = options.serialize;
}
// Create an asynchronous handler
handler = LayoutManager._makeAsync(options, _.bind(done, root, context));
// Make a new deferred purely for the fetch function
handler.fetch = options.deferred();
// Assign the handler internally to be resolved once its inside the
// parent element.
root.__manager__.handler = handler;
// Set the url to the prefix + the view's template property.
if (_.isString(template)) {
url = root._prefix + template;
}
// Check if contents are already cached
if (contents = LayoutManager.cache(url)) {
done(context, contents, url);
return handler;
}
// Fetch layout and template contents
if (_.isString(template)) {
contents = options.fetch.call(handler, root._prefix + template);
// If its not a string just pass the object/function/whatever
} else if (template != null) {
contents = options.fetch.call(handler, template);
}
// If the function was synchronous, continue execution.
if (!handler._isAsync) {
done(context, contents);
}
return handler;
}
};
},
// Accept either a single view or an array of views to clean of all DOM events
// internal model and collection references and all Backbone.Events.
cleanViews: function(views) {
// Clear out all existing views
_.each([].concat(views), function(view) {
// Remove all custom events attached to this View
view.unbind();
// Ensure all nested views are cleaned as well
if (view.views) {
_.each(view.views, function(view) {
LayoutManager.cleanViews(view);
});
}
// If a custom cleanup method was provided on the view, call it after
// the initial cleanup is done
if (_.isFunction(view.cleanup)) {
view.cleanup.call(view);
}
});
},
// Cache templates into LayoutManager._cache
cache: function(path, contents) {
// If template path is found in the cache, return the contents.
if (path in this._cache) {
return this._cache[path];
// Ensure path and contents aren't undefined
} else if (path != null && contents != null) {
return this._cache[path] = contents;
}
// If template is not in the cache, return undefined.
},
// This static method allows for global configuration of LayoutManager.
configure: function(opts) {
_.extend(LayoutManager.prototype.options, opts);
},
// Configure a View to work with the LayoutManager plugin.
setupView: function(view, options) {
var proto = Backbone.LayoutManager.prototype;
// Extend the options with the prototype and passed options.
options = view.options = _.defaults(options || {}, proto.options);
// Ensure necessary properties are set.
_.defaults(view, {
// Ensure a view always has a views object.
views: {},
// Internal state object used to store whether or not a View has been
// taken over by layout manager and if it has been rendered into the DOM.
__manager__: {}
});
// If the user provided their own render override, use that instead of the
// default.
if (this.render !== proto.render && !this._render) {
this._render = this.render;
this.render = proto.render;
}
// By default the original Remove function is the Backbone.View one.
view._remove = Backbone.View.prototype.remove;
// If the user provided their own remove override, use that instead of the
// default.
if (view.remove !== proto.remove) {
view._remove = view.remove;
view.remove = proto.remove;
}
// Default the prefix to an empty string.
view._prefix = "";
// Set the internal views
if (options.views) {
view.setViews(options.views);
}
// Ensure the template is mapped over
if (view.template) {
options.template = view.template;
}
},
// Completely remove all subViews
removeView: function(root, append) {
// Can be used static or as a method.
if (!_.isObject(root)) {
root = root || this;
append = root;
}
// Iterate over all of the view's subViews.
_.each(root.views, function(views) {
// If the append flag is set, only prune arrays.
if (append && !_.isArray(views)) {
return;
}
// Clear out all existing views
_.each([].concat(views), function(view) {
// Remove the View completely
view.remove();
// Ensure all nested views are cleaned as well.
view.getViews().each(function(view) {
LayoutManager.removeView(view, append);
});
});
});
}
});
// Ensure all Views always have access to get/set/insert(View/Views).
_.each(["get", "set", "insert"], function(method) {
var backboneProto = Backbone.View.prototype;
var layoutProto = LayoutManager.prototype;
// Attach the singular form.
backboneProto[method + "View"] = layoutProto[method + "View"];
// Attach the plural form.
backboneProto[method + "Views"] = layoutProto[method + "Views"];
});
_.extend(Backbone.View.prototype, {
// Add the ability to remove all Views.
removeView: LayoutManager.removeView,
// Add options into the prototype.
_options: LayoutManager.prototype._options
});
// Convenience assignment to make creating Layout's slightly shorter.
Backbone.Layout = Backbone.LayoutManager = LayoutManager;
// Default configuration options; designed to be overriden.
LayoutManager.prototype.options = {
// Layout and template properties can be assigned here to prefix
// template/layout names.
paths: {},
// Can be used to supply a different deferred that implements Promises/A.
deferred: function() {
return $.Deferred();
},
// Fetch is passed a path and is expected to return template contents as a
// function or string.
fetch: function(path) {
return _.template($(path).html());
},
// This is really the only way you will want to partially apply a view into
// a layout. Its entirely possible you'll want to do it differently, so
// this method is available to change.
partial: function(root, name, el, append) {
// If no selector is specified, assume the parent should be added to.
var $root = name ? $(root).find(name) : $(root);
// If no root found, return false
if (!$root.length) {
return false;
}
// Use the append method if append argument is true.
this[append ? "append" : "html"]($root, el);
// If successfully added, return true
return true;
},
// Override this with a custom HTML method, passed a root element and an
// element to replace the innerHTML with.
html: function(root, el) {
$(root).html(el);
},
// Very similar to HTML except this one will appendChild.
append: function(root, el) {
$(root).append(el);
},
// Return a deferred for when all promises resolve/reject.
when: function(promises) {
return $.when.apply(null, promises);
},
// By default, render using underscore's templating.
render: function(template, context) {
return template(context);
}
};
})(this);