-
Notifications
You must be signed in to change notification settings - Fork 12
/
dynamic_template.js
616 lines (520 loc) · 17.2 KB
/
dynamic_template.js
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
/*****************************************************************************/
/* Imports */
/*****************************************************************************/
var debug = Iron.utils.debug('iron:dynamic-template');
var assert = Iron.utils.assert;
var get = Iron.utils.get;
var camelCase = Iron.utils.camelCase;
/*****************************************************************************/
/* Private */
/*****************************************************************************/
var typeOf = function (value) {
return Object.prototype.toString.call(value);
};
/*****************************************************************************/
/* DynamicTemplate */
/*****************************************************************************/
/**
* Render a component to the page whose template and data context can change
* dynamically, either from code or from helpers.
*
*/
DynamicTemplate = function (options) {
this._id = Random.id();
this.options = options = options || {};
this._template = options.template;
this._defaultTemplate = options.defaultTemplate;
this._content = options.content;
this._data = options.data;
this._templateDep = new Tracker.Dependency;
this._dataDep = new Tracker.Dependency;
this._lookupHostDep = new Tracker.Dependency;
this._lookupHostValue = null;
this._hooks = {};
this._eventMap = null;
this._eventHandles = null;
this._eventThisArg = null;
this.name = options.name || this.constructor.prototype.name || 'DynamicTemplate';
// has the Blaze.View been created?
this.isCreated = false;
// has the Blaze.View been destroyed and not created again?
this.isDestroyed = false;
};
/**
* Get or set the template.
*/
DynamicTemplate.prototype.template = function (value) {
if (arguments.length === 1 && value !== this._template) {
this._template = value;
this._templateDep.changed();
return;
}
if (arguments.length > 0)
return;
this._templateDep.depend();
// do we have a template?
if (this._template)
return (typeof this._template === 'function') ? this._template() : this._template;
// no template? ok let's see if we have a default one set
if (this._defaultTemplate)
return (typeof this._defaultTemplate === 'function') ? this._defaultTemplate() : this._defaultTemplate;
};
/**
* Get or set the default template.
*
* This function does not change any dependencies.
*/
DynamicTemplate.prototype.defaultTemplate = function (value) {
if (arguments.length === 1)
this._defaultTemplate = value;
else
return this._defaultTemplate;
};
/**
* Clear the template and data contexts.
*/
DynamicTemplate.prototype.clear = function () {
//XXX do we need to clear dependencies here too?
this._template = undefined;
this._data = undefined;
this._templateDep.changed();
};
/**
* Get or set the data context.
*/
DynamicTemplate.prototype.data = function (value) {
if (arguments.length === 1 && value !== this._data) {
this._data = value;
this._dataDep.changed();
return;
}
this._dataDep.depend();
return typeof this._data === 'function' ? this._data() : this._data;
};
/**
* Create the view if it hasn't been created yet.
*/
DynamicTemplate.prototype.create = function (options) {
var self = this;
if (this.isCreated) {
throw new Error("DynamicTemplate view is already created");
}
this.isCreated = true;
this.isDestroyed = false;
var templateVar = ReactiveVar(null);
var view = Blaze.View('DynamicTemplate', function () {
var thisView = this;
// create the template dependency here because we need the entire
// dynamic template to re-render if the template changes, including
// the Blaze.With view.
var template = templateVar.get();
return Blaze.With(function () {
// NOTE: This will rerun anytime the data function invalidates this
// computation OR if created from an inclusion helper (see note below) any
// time any of the argument functions invlidate the computation. For
// example, when the template changes this function will rerun also. But
// it's probably generally ok. The more serious use case is to not
// re-render the entire template every time the data context changes.
var result = self.data();
if (typeof result !== 'undefined')
// looks like data was set directly on this dynamic template
return result;
else
// return the first parent data context that is not inclusion arguments
return DynamicTemplate.getParentDataContext(thisView);
}, function () {
return self.renderView(template);
});
});
view.onViewCreated(function () {
this.autorun(function () {
templateVar.set(self.template());
});
});
// wire up the view lifecycle callbacks
_.each(['onViewCreated', 'onViewReady', '_onViewRendered', 'onViewDestroyed'], function (hook) {
view[hook](function () {
// "this" is the view instance
self._runHooks(hook, this);
});
});
view._onViewRendered(function () {
// avoid inserting the view twice by accident.
self.isInserted = true;
if (view.renderCount !== 1)
return;
self._attachEvents();
});
view.onViewDestroyed(function () {
// clean up the event handlers if
// the view is destroyed
self._detachEvents();
});
view._templateInstance = new Blaze.TemplateInstance(view);
view.templateInstance = function () {
// Update data, firstNode, and lastNode, and return the TemplateInstance
// object.
var inst = view._templateInstance;
inst.data = Blaze.getData(view);
if (view._domrange && !view.isDestroyed) {
inst.firstNode = view._domrange.firstNode();
inst.lastNode = view._domrange.lastNode();
} else {
// on 'created' or 'destroyed' callbacks we don't have a DomRange
inst.firstNode = null;
inst.lastNode = null;
}
return inst;
};
this.view = view;
view.__dynamicTemplate__ = this;
view.name = this.name;
return view;
};
DynamicTemplate.prototype.renderView = function (template) {
var self = this;
// NOTE: When DynamicTemplate is used from a template inclusion helper
// like this {{> DynamicTemplate template=getTemplate data=getData}} the
// function below will rerun any time the getData function invalidates the
// argument data computation.
var tmpl = null;
// is it a template name like "MyTemplate"?
if (typeof template === 'string') {
tmpl = Template[template];
if (!tmpl)
// as a fallback double check the user didn't actually define
// a camelCase version of the template.
tmpl = Template[camelCase(template)];
if (!tmpl) {
tmpl = Blaze.With({
msg: "Couldn't find a template named " + JSON.stringify(template) + " or " + JSON.stringify(camelCase(template))+ ". Are you sure you defined it?"
}, function () {
return Template.__IronRouterDynamicTemplateError__;
});
}
} else if (typeOf(template) === '[object Object]') {
// or maybe a view already?
tmpl = template;
} else if (typeof self._content !== 'undefined') {
// or maybe its block content like
// {{#DynamicTemplate}}
// Some block
// {{/DynamicTemplate}}
tmpl = self._content;
}
return tmpl;
};
/**
* Destroy the dynamic template, also destroying the view if it exists.
*/
DynamicTemplate.prototype.destroy = function () {
if (this.isCreated) {
Blaze.remove(this.view);
this.view = null;
this.isDestroyed = true;
this.isCreated = false;
}
};
/**
* View lifecycle hooks.
*/
_.each(['onViewCreated', 'onViewReady', '_onViewRendered', 'onViewDestroyed'], function (hook) {
DynamicTemplate.prototype[hook] = function (cb) {
var hooks = this._hooks[hook] = this._hooks[hook] || [];
hooks.push(cb);
return this;
};
});
DynamicTemplate.prototype._runHooks = function (name, view) {
var hooks = this._hooks[name] || [];
var hook;
for (var i = 0; i < hooks.length; i++) {
hook = hooks[i];
// keep the "thisArg" pointing to the view, but make the first parameter to
// the callback teh dynamic template instance.
hook.call(view, this);
}
};
DynamicTemplate.prototype.events = function (eventMap, thisInHandler) {
var self = this;
this._detachEvents();
this._eventThisArg = thisInHandler;
var boundMap = this._eventMap = {};
for (var key in eventMap) {
boundMap[key] = (function (key, handler) {
return function (e) {
var data = Blaze.getData(e.currentTarget);
if (data == null) data = {};
var tmplInstance = self.view.templateInstance();
return handler.call(thisInHandler || this, e, tmplInstance, data);
}
})(key, eventMap[key]);
}
this._attachEvents();
};
DynamicTemplate.prototype._attachEvents = function () {
var self = this;
var thisArg = self._eventThisArg;
var boundMap = self._eventMap;
var view = self.view;
var handles = self._eventHandles;
if (!view)
return;
var domrange = view._domrange;
if (!domrange)
throw new Error("no domrange");
var attach = function (range, element) {
_.each(boundMap, function (handler, spec) {
var clauses = spec.split(/,\s+/);
// iterate over clauses of spec, e.g. ['click .foo', 'click .bar']
_.each(clauses, function (clause) {
var parts = clause.split(/\s+/);
if (parts.length === 0)
return;
var newEvents = parts.shift();
var selector = parts.join(' ');
handles.push(Blaze._EventSupport.listen(
element, newEvents, selector,
function (evt) {
if (! range.containsElement(evt.currentTarget))
return null;
var handlerThis = self._eventThisArg || this;
var handlerArgs = arguments;
//XXX which view should this be? What if the event happened
//somwhere down the hierarchy?
return Blaze._withCurrentView(view, function () {
return handler.apply(handlerThis, handlerArgs);
});
},
range, function (r) {
return r.parentRange;
}));
});
});
};
if (domrange.attached)
attach(domrange, domrange.parentElement);
else
domrange.onAttached(attach);
};
DynamicTemplate.prototype._detachEvents = function () {
_.each(this._eventHandles, function (h) { h.stop(); });
this._eventHandles = [];
};
var attachEventMaps = function (range, element, eventMap, thisInHandler) {
_.each(eventMap, function (handler, spec) {
var clauses = spec.split(/,\s+/);
// iterate over clauses of spec, e.g. ['click .foo', 'click .bar']
_.each(clauses, function (clause) {
var parts = clause.split(/\s+/);
if (parts.length === 0)
return;
var newEvents = parts.shift();
var selector = parts.join(' ');
handles.push(Blaze._EventSupport.listen(
element, newEvents, selector,
function (evt) {
if (! range.containsElement(evt.currentTarget))
return null;
var handlerThis = thisInHandler || this;
var handlerArgs = arguments;
return Blaze._withCurrentView(view, function () {
return handler.apply(handlerThis, handlerArgs);
});
},
range, function (r) {
return r.parentRange;
}));
});
});
};
/**
* Insert the Layout view into the dom.
*/
DynamicTemplate.prototype.insert = function (options) {
options = options || {};
if (this.isInserted)
return;
this.isInserted = true;
var el = options.el || document.body;
var $el = $(el);
if ($el.length === 0)
throw new Error("No element to insert layout into. Is your element defined? Try a Meteor.startup callback.");
if (!this.view)
this.create(options);
Blaze.render(this.view, $el[0], options.nextNode, options.parentView);
return this;
};
/**
* Reactively return the value of the current lookup host or null if there
* is no lookup host.
*/
DynamicTemplate.prototype._getLookupHost = function () {
// XXX this is called from the Blaze overrides so we can't create a dep
// here for every single lookup. Will revisit.
//this._lookupHostDep.depend();
return this._lookupHostValue;
};
/**
* Set the reactive value of the lookup host.
*
*/
DynamicTemplate.prototype._setLookupHost = function (host) {
var self = this;
if (self._lookupHostValue !== host) {
self._lookupHostValue = host;
Deps.afterFlush(function () {
// if the lookup host changes and the template also changes
// before the next flush cycle, this gives the new template
// a chance to render, and the old template to be torn off
// the page (including stopping its computation) before the
// lookupHostDep is changed.
self._lookupHostDep.changed();
});
}
return this;
};
/*****************************************************************************/
/* DynamicTemplate Static Methods */
/*****************************************************************************/
/**
* Get the first parent data context that are not inclusion arguments
* (see above function). Note: This function can create reactive dependencies.
*/
DynamicTemplate.getParentDataContext = function (view) {
return DynamicTemplate.getDataContext(view && view.parentView);
};
/**
* Get the first data context that is not inclusion arguments.
*/
DynamicTemplate.getDataContext = function (view) {
while (view) {
if (view.name === 'with' && !view.__isTemplateWith)
return view.dataVar.get();
else
view = view.parentView;
}
return null;
};
/**
* Get inclusion arguments, if any, from a view.
*
* Uses the __isTemplateWith property set when a parent view is used
* specificially for a data context with inclusion args.
*
* Inclusion arguments are arguments provided in a template like this:
* {{> yield "inclusionArg"}}
* or
* {{> yield region="inclusionArgValue"}}
*/
DynamicTemplate.getInclusionArguments = function (view) {
var parent = view && view.parentView;
if (!parent)
return null;
if (parent.__isTemplateWith)
return parent.dataVar.get();
return null;
};
/**
* Given a view, return a function that can be used to access argument values at
* the time the view was rendered. There are two key benefits:
*
* 1. Save the argument data at the time of rendering. When you use lookup(...)
* it starts from the current data context which can change.
* 2. Defer creating a dependency on inclusion arguments until later.
*
* Example:
*
* {{> MyTemplate template="MyTemplate"
* var args = DynamicTemplate.args(view);
* var tmplValue = args('template');
* => "MyTemplate"
*/
DynamicTemplate.args = function (view) {
return function (key) {
var data = DynamicTemplate.getInclusionArguments(view);
if (data) {
if (key)
return data[key];
else
return data;
}
return null;
};
};
/**
* Inherit from DynamicTemplate.
*/
DynamicTemplate.extend = function (props) {
return Iron.utils.extend(this, props);
};
DynamicTemplate.findFirstLookupHost = function (view) {
var host;
var helper;
assert(view instanceof Blaze.View, "view must be a Blaze.View");
while (view) {
if (view.__dynamicTemplate__) {
// creates a reactive dependency.
var host = view.__dynamicTemplate__._getLookupHost();
if (host) return host;
} else {
view = view.parentView;
}
}
return undefined;
};
DynamicTemplate.findLookupHostWithProperty = function (view, key) {
var host;
var prop;
assert(view instanceof Blaze.View, "view must be a Blaze.View");
while (view) {
if (view.__dynamicTemplate__) {
// creates a reactive dependency
var host = view.__dynamicTemplate__._getLookupHost();
if (host && get(host, key)) {
return host;
}
}
view = view.parentView;
}
return undefined;
};
/**
* Find a lookup host that has a given helper and returns the host. Note,
* this will create a reactive dependency on each dynamic template's getLookupHost
* function. This is required becuase we need to rerun the entire lookup if
* the host changes or is added or removed later, anywhere in the chain.
*/
DynamicTemplate.findLookupHostWithHelper = function (view, helperKey) {
var host;
var helper;
assert(view instanceof Blaze.View, "view must be a Blaze.View");
while (view) {
if (view.__dynamicTemplate__) {
// creates a reactive dependency
var host = view.__dynamicTemplate__._getLookupHost();
if (host && get(host, 'constructor', '_helpers', helperKey)) {
return host;
}
}
view = view.parentView;
}
return undefined;
};
/*****************************************************************************/
/* UI Helpers */
/*****************************************************************************/
if (typeof Template !== 'undefined') {
UI.registerHelper('DynamicTemplate', new Template('DynamicTemplateHelper', function () {
var args = DynamicTemplate.args(this);
return new DynamicTemplate({
data: function () { return args('data'); },
template: function () { return args('template'); },
content: this.templateContentBlock
}).create();
}));
}
/*****************************************************************************/
/* Namespacing */
/*****************************************************************************/
Iron.DynamicTemplate = DynamicTemplate;