-
Notifications
You must be signed in to change notification settings - Fork 2k
/
g-component.html
891 lines (794 loc) · 27.4 KB
/
g-component.html
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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
<element name="g-component">
<script>
// FOUC prevent (to opt-in, set opacity: 0 on body)
window.addEventListener('WebComponentsReady', function() {
document.body.style.webkitTransition = "opacity 0.4s";
document.body.style.opacity = 1;
});
// log control
var log = {
ready: 1,
events: 0,
data: 0
};
log = window.logFlags || log;
// decorate HTMLElementElement with toolkit API
HTMLElementElement.prototype.component = component;
// entry point for declarative component definition
function component(inDefinition) {
// ensure non-null definition
var definition = inDefinition || {};
// use information from HTMLElementElement attributes
var attributes = this.element.attributes;
// install boilerplate callbacks
this.lifecycle({
shadowRootCreated: function(inRoot) {
initializeRoot.call(this, inRoot, definition);
},
created: function(/*inSuper*/) {
instanceReady.call(this);
}
});
// parse declared attributes into imperative form
publishAttributes(attributes[conventions.ATTRIBUTES_ATTRIBUTE],
definition);
// parse declared on-* delegates into imperative form
parseHostEvents(attributes, definition);
// construct a prototype from our sugared definition
var prototype = desugar(definition, this.extendsName);
// register this prototype with it's tag name
register(this.name, prototype);
// install our prototype
this.generatedConstructor.prototype = prototype;
};
function initializeRoot(inRoot) {
// we only want to do somes tasks per-instance, but they must
// be done before root initializations, and we have no other
// entry point, so we have to multiplex this method
if (!this.hasOwnProperty('$protected')) {
instanceCreated.call(this);
}
if (inRoot) {
rootCreated.call(this, inRoot);
}
};
// component lifecycle
function instanceCreated() {
// instance our protected interface
this.$protected = Object.create(this.$protected);
// point our protected instance at our node instance
this.$protected.node = this;
};
function rootCreated(inRoot) {
// set shadow-root model
inRoot.model = this.$protected;
// map id's to nodes, for nodes with id's
marshalNodeReferences.call(this.$protected, inRoot);
// parse and apply model binding markup in DOM
bindModel.call(this, localChildNodes(inRoot));
// accumulate events of interest
// TODO(sjmiles): ideally on native we set up listeners directly on inRoot,
// under shim inRoot does not participate in event bubbling
this.__events = accumulateEvents(inRoot, this.__events);
//console.log('[%s]:', this.localName, this.__events);
};
function instanceReady() {
// delegate host events
//bindHostEvents.call(this.$protected);
accumulateHostEvents.call(this.$protected, this.__events);
// TODO(sjmiles): ideally delegated events are set up per root
// not on the host node (see above)
bindAccumulatedEvents(this, this.__events);
// initialize our Observable aspect
Observable.call(this.$protected);
takeAttributes.call(this.$protected);
// call ready hook
this.$protected.ready();
// TODO(sjmiles): explain succinctly why this dirtyCheck is here
window.dirtyCheck();
log.ready && console.log('[%s#%s] ready', this.localName, this.id || '');
};
// helper functions
var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);
// helper for ShadowDOM shim compatibility
var deref = function(inNode) {
// return the real node if inNode is a placeholder (Changeling)
return inNode && (inNode.baby || inNode);
};
var publishAttributes = function(inAttributes, inDefinition) {
if (inAttributes) {
var pd = conventions.PUBLISH_DIRECTIVE;
// need a publish block to extend
var pub = inDefinition[pd] = inDefinition[pd] || {};
// use the value of the attributes-attribute
var a$ = inAttributes.value;
// attributes='a b c' or attributes='a,b,c'
var names = a$.split(a$.indexOf(',') >= 0 ? ',' : ' ');
// record each name for publishing
names.forEach(function(p) {
pub[p.trim()] = null;
});
}
};
var parseHostEvents = function(inAttributes, inDefinition) {
inDefinition.eventDelegates = mixin(inDefinition.eventDelegates,
parseEvents(inAttributes));
};
var parseEvents = function(inAttributes) {
var events = {};
if (inAttributes) {
var prefix = conventions.CUSTOM_EVENT_PREFIX;
for (var i=0, a; a=inAttributes[i]; i++) {
if (a.name.slice(0, prefix.length) == prefix) {
events[a.name.slice(prefix.length)] = a.value;
}
}
}
return events;
};
// conventional names for automation
var conventions = {
ATTRIBUTES_ATTRIBUTE: 'attributes',
PUBLISH_DIRECTIVE: 'publish',
PROPERTY_CHANGED_SUFFIX: 'Changed',
CUSTOM_EVENT_PREFIX: 'on-',
DELEGATES_DIRECTIVE: 'bind',
DELEGATE_OUT_SUFFIX: 'Output',
DELEGATE_IN_SUFFIX: 'Input'
};
//
// OOP abstractions
//
// it's convenient to keep track of our own components
// for protected inheritance
function desugar(inDefinition, inExtendsName) {
// prototype to extend
var base = registry[inExtendsName] || BasePrototype;
// extend prototype
var prototype = extend(inDefinition, base);
// publish public properties
publish(prototype);
//
// more desugaring
//
// return extended prototype
return prototype;
};
// it's convenient (but probably redundant) to maintain
// an internal registry
var registry = {};
function register(inName, inPrototype) {
// cache prototype
return registry[inName] = inPrototype;
};
// produce a prototype from inDefinition which extends inBase
function extend(inDefinition, inBase) {
var prototype = Object.create(inBase);
// use definition directly to avoid a mixin step
// (caveats: can't reuse definitions, relies on __proto__)
prototype.$protected = inDefinition;
prototype.$protected.__proto__ = inBase.$protected;
return prototype;
};
// publishing is a sugaring mechanism where properties
// specified in a 'publish' block are forwarded to the
// public interface via get/set pairs and bound functions
function publish(inPrototype) {
var $protected = inPrototype.$protected;
// publish properties via 'publish' directive
var pd = conventions.PUBLISH_DIRECTIVE;
if ($protected.hasOwnProperty(pd)) {
var $public = $protected[pd];
// install public properties on $protected
for (var n in $public) {
// do not overwrite default values already (directly) on prototype
if (!$protected.hasOwnProperty(n)) {
copyProperty(n, $public, $protected)
}
}
// publish public properties to master prototype
publishProperties($public, $protected, inPrototype);
}
}
// copy property 'name' from src to obj
var copyProperty = function(name, src, obj) {
var g = src.__lookupGetter__(name);
if (g) {
obj.__defineGetter__(name, g);
} else {
obj[name] = src[name];
}
var s = src.__lookupSetter__(name);
if (s) {
obj.__defineSetter__(name, s);
}
};
// copy all properties from inProps (et al) to inObj
var mixin = function(inObj/*, inProps, inMoreProps, ...*/) {
var obj = inObj || {};
var p$ = Array.prototype.slice.call(arguments, 1);
for (var i=0, p; (p=p$[i]); i++) {
for (var n in p) {
copyProperty(n, p, obj);
}
}
return obj;
};
// publish properties identified by inProperties from inSource to inTarget
function publishProperties(inProperties, inSource, inTarget) {
for (var n in inProperties) {
publishProperty(inSource, n, inTarget);
}
};
// make inSource[inName] available on inTarget as a getter/setter
// pair or a method bound to this.$protected
function publishProperty(inSource, inName, inTarget) {
// access property value (unless it is a getter itself)
var value = (!inSource.__lookupGetter__(inName)) && inSource[inName];
if (typeof value == 'function') {
inTarget[inName] = function() {
return value.apply(this.$protected, arguments);
}
} else {
// TODO(sjmiles): can't remember why I needed to install
// the property before defining get/set
// if it turns out we do need this, beware of overrides
// where there is already a setter and there are side effects
//inTarget[inName] = null;
Object.defineProperty(inTarget, inName, {
get: function() {
return this.$protected[inName];
},
set: function(inValue) {
this.$protected.setProperty(inName, inValue);
}
});
}
};
//
// Base API
//
// data observer abstraction
// this implementation uses MDV polyfill
var Observable = function() {
api.activate.call(this);
};
var watch_blacklist = {$: 1, node: 1, eventDelegates: 1, publish: 1};
var api = Observable.api = {
activate: function () {
var watched = {};
Model.observePropertySet(this, function(inChange) {
api.propertySetChanged.call(this, inChange, watched);
}.bind(this));
api.watchAll.call(this, watched);
},
propertySetChanged: function(inChange, inWatched) {
if (inChange.mutation == 'add') {
//log.watch && console.log('[%s] propertySetChanged: adding watch for [%s]', this.node.localName, inChange.propertyName);
api.addWatch.call(this, inChange.propertyName, null, inWatched);
//this.propertyChanged(inChange.propertyName);
}
},
watchable: function(inName, inWatched) {
return (inName[0] != '_')
&& !(inName in Object.prototype)
&& !inWatched[inName]
&& (typeof this[inName] != 'function')
&& !this.__lookupGetter__(inName)
&& !watch_blacklist[inName];
},
addWatch: function(inName, inWatched) {
if (api.watchable.call(this, inName, inWatched)) {
log.watch && console.log('[' + this.node.localName + '] watching [' + inName + ']');
inWatched[inName] = true;
Model.observe(this, inName, function(inNew, inOld) {
log.data && console.log('[%s#%s] watch: [%s] now [%s] was [%s]', this.node.localName, this.node.id || '', inName, this[inName], inOld);
this.propertyChanged(inName, inOld);
}.bind(this));
}
},
watchAll: function(inWatched) {
for (var n in this) {
api.addWatch.call(this, n, inWatched);
}
}
};
Observable.prototype = {
propertyChanged: function(inName, inOldValue) {
//log.data && console.log('[%s#%s] propertyChanged: [%s] now [%s] was [%s]', this.node.localName, this.node.id || '', inName, this[inName], inOldValue);
var fn = inName + 'Changed';
if (this[fn] && !Observable._squelch) {
this[fn](inOldValue);
}
},
setProperty: function(inName, inValue, inSilent) {
Observable._squelch = inSilent;
try {
this[inName] = inValue;
} finally {
Observable._squelch = false;
}
}
};
// super call implementation
var $super = (function() {
// TODO(sjmiles): will not work with mixins because
// the memoization strategy assumes
// each function exists on only one prototype chain
// (i.e. we use the function object for memoizing)
var nextSuper = function(inProto, inName, inCaller) {
// look for an inherited prototype that implements inName
var proto = inProto;
while (proto &&
(!proto.hasOwnProperty(inName) || proto[inName] == inCaller)) {
proto = proto.__proto__;
}
return proto;
};
var memoizeSuper = function(inMethod, inName, inProto) {
// find and cache next prototype containing inName
// we need the prototype so we can another lookup
// from here
inMethod._super = nextSuper(inProto, inName, inMethod);
if (inMethod._super) {
// _super is a prototype, the actual method is _super[inName]
// tag super method with it's name for further lookups
inMethod._super[inName]._nom = inName;
}
};
var nameInThis = function(inValue) {
for (var n in this) {
if (this[n] == inValue) {
return n;
}
}
};
return function(inArgs) {
// since we are thunking a method call, performance is important
// here: memoize all lookups, once memoized the fast path
// calls no helper functions
//
// find the caller (can't be strict because of 'caller')
var caller = this.$super.caller;
// memoization for 'name of method'
var nom = caller._nom;
if (!nom) {
// once per call chain
nom = caller._nom = nameInThis.call(this, caller);
if (!nom) {
console.warn('called super() on a method not in "this"');
return;
}
}
// super prototype is either cached or we have to find it
// by searching __proto__ (at the 'top')
if (!('_super' in caller)) {
memoizeSuper(caller, nom, this.__proto__);
}
// memoized next implementation prototype
var _super = caller._super;
if (!_super) {
// if _super is falsey, there is no super implementation
console.warn('called $super(' + nom + ') where there is no super implementation');
} else {
// our super function
var fn = _super[nom];
// memoize information so 'fn' can call 'super'
if (!('_super' in fn)) {
memoizeSuper(fn, nom, _super);
}
// invoke the inherited method
// if 'fn' is not function valued, this will throw
return fn.apply(this, inArgs || []);
}
};
})();
// (protected) Base API
var ProtectedBase = {
ready: function() {
},
$super: $super,
asyncMethod: function(inMethod, inArgs, inTimeout) {
var args = (inArgs && inArgs.length) ? inArgs : [inArgs];
return window.setTimeout(function() {
this[inMethod].apply(this, args);
}.bind(this), inTimeout || 0);
},
dispatch: function(inMethodName, inArguments) {
if (this[inMethodName]) {
this[inMethodName].apply(this, inArguments);
}
},
send: function(inType, inDetail, inToNode) {
var node = inToNode || this.node;
log.events && console.log('[%s]: sending [%s]', node.localName, inType);
node.dispatchEvent(
new CustomEvent(inType, {bubbles: true, detail: inDetail})
);
},
asend: function(/*inType, inDetail*/) {
this.asyncMethod("send", arguments);
},
findDistributedTarget: function(inTarget, inNodes) {
// find first ancestor of target (including itself) that
// is in inNodes, if any
var n = inTarget;
while (n && n != this) {
var i = Array.prototype.indexOf.call(inNodes, n);
if (i >= 0) {
return i;
}
n = n.parentNode;
}
}
};
// TODO(sjmiles): deprecated
ProtectedBase.fireEvent = ProtectedBase.send;
// use ProtectedBase directly to avoid a mixin step
// (caveat: relies on __proto__)
ProtectedBase.__proto__ = Object.create(Observable.prototype);
var BasePrototype = {
// base $protected implementation is Observable
$protected: ProtectedBase
};
// ShadowDOM tree walking
// TODO(sjmiles): should be provided by ShadowDOM object
// TODO(sjmiles): make unit tests and stabilize the tree walking concepts
// once and for all
var localChildNodes = function(inNode) {
return (inNode.tagName == 'CONTENT' && [])
|| (inNode.lightDOM && inNode.lightDOM.childNodes)
|| inNode.insertions
|| inNode.childNodes
;
};
var localParentNode = function(inNode) {
var node = inNode.host || inNode.parentNode;
if (node) {
if (node.isLightDOM) {
node = node.host;
}
node = node.changeling || node;
}
return node;
};
//
// reference marshalling
//
// locate nodes with id and store references to them in this.$ hash
var marshalNodeReferences = function(inRoot) {
// establish $ instance variable
this.$ = this.$ || {};
// populate $ from nodes with ID from the LOCAL tree
if (inRoot) {
var nodes = ShadowDOM.localQueryAll(inRoot, "[id]");
forEach(nodes, function(n) {
this.$[n.id] = deref(n);
}, this);
}
};
//
// model bindings
//
// convert {{macro}} strings in markup into MDV bindings
//
// MDV usually does this work but requires an additional
// nested template and functions asynchronously
function bindModel(inNodes) {
log.bind && console.group("[%s] bindModel", this.localName);
_bindModel.call(this, inNodes);
log.bind && console.groupEnd();
};
function _bindModel(inNodes) {
forEach(inNodes, bindNodeModel, this);
};
function bindNodeModel(inNode) {
var n = deref(inNode);
// node's binding model is this component's protected object
n.model = this.$protected;
if (n.nodeName == '#text') {
// text-node binding
bindMustache.call(this, n, n.textContent);
} else if (n.tagName !== 'TEMPLATE') {
// scan for bindings in attributes
if (n.attributes) {
forEach(n.attributes, function(a) {
bindMustache.call(this, n, a.name, a.value);
}, this);
}
// walking the LOCAL tree
_bindModel.call(this, localChildNodes(n));
}
};
function bindMustache(inNode, inName, inValue) {
// ad-hoc component test
if (inNode.$protected) {
var m = inValue.match(bindMustache.pattern);
if (m) {
var source = m[1];
var target = propertyForAttribute.call(inNode.$protected, inName);
if (source && target) {
bindProperties(this, source, inNode, target);
}
}
} else {
if ((inValue || inName).search(bindMustache.pattern) >= 0) {
inNode.addBinding(inName, inValue);
log.bind && console.log('[%s] bindMustache: [%s] to [%s]%s',
this.localName, inValue || inName, (inNode.localName || '#text'),
inValue ? '.[' + inValue + ']' : '');
}
}
};
bindMustache.pattern = /\{\{([^{}]*)}}/;
// property binding extensions to MDV
function bindProperties(inA, inPropA, inB, inPropB) {
log.bind && console.log('[%s] bindProperties [%s] to [%s].[%s]', inA.localName, inPropA, inB.localName, inPropB);
_bindProperties(inA.$protected, inPropA, inB.$protected, inPropB);
// TODO(sjmiles): explain succinctly why this dirtyCheck is here
window.dirtyCheck();
};
function _getProp(parts, create, context) {
var obj = context || window;
for(var i=0, p; obj && (p=parts[i]); i++){
obj = (p in obj ? obj[p] : (create ? obj[p]={} : undefined));
}
return obj;
};
// TODO(sjmiles): parameters crufty for the usage below, simplify
function setProperty(name, value, context) {
var parts = name.split("."), p = parts.pop(),
obj = _getProp(parts, true, context);
return obj && p ? (obj[p]=value) : undefined;
};
function getProperty(name, create, context) {
return _getProp(name.split("."), create, context);
};
function _bindProperties(inA, inPropA, inB, inPropB) {
var value = getProperty(inPropA, true, inA);
log.data && console.log('[%s] _bindProperties: sending [%s] (%s) to [%s].[%s]', inA.node.localName, inPropA, value, inB.node.localName, inPropB);
setProperty(inPropB, value, inB);
bindProperty(inA, inPropA, inB, inPropB);
bindProperty(inB, inPropB, inA, inPropA);
};
function bindProperty(inA, inPropA, inB, inPropB) {
Model.observe(inA, inPropA, function(inNew) {
// intermediate changes are observed, but are irrelevant
// we only propagate when the value stabilizes
if (getProperty(inPropA, false, inA) === inNew) {
// probably redundant, but prevent circularity right here
if (getProperty(inPropB, false, inB) !== inNew) {
log.data && console.log('[%s] bindProperty: propagating [%s] (%s) to [%s].[%s]', inA.node.localName, inPropA, inNew, inB.node.localName, inPropB);
setProperty(inPropB, inNew, inB);
}
}
});
};
//
// attribute processing
//
// propagate initial attribute values into properties as a batch,
// invoking side-effects only after all values are set
function takeAttributes() {
// accumulate a record of all non-default attribute values
// so we can invoke side-effects after all values are initialized
//var changed = [];
// for each attribute
forEach(this.node.attributes, function(a) {
// try to match this attribute to a property (attributess are
// all lower-case, so this is case-insensitive search)
var name = propertyForAttribute.call(this, a.name);
if (name) {
// filter out 'mustached' values, these are to be
// replaced with bound-data and are not yet values
// themselves
if (a.value.search(bindMustache.pattern) >= 0) {
return;
}
// deserialize Boolean or Number values from attribute
var value = deserializeValue(a.value);
//console.log('takeAttributes: ', a.name, a.value);
// only act if the value has changed
if (this[name] !== value) {
// track values that differ from property values
//changed.push({name: name, old: this[name]});
// install new value (has side-effects)
this[name] = value;
}
}
}, this);
//Model.dirtyCheck();
/*
// batch invoke side-effects
changed.forEach(function(c) {
propertyChanged.call(this, c.name, c.old);
}, this);
*/
};
// find the public property identified by inAttributeName
function propertyForAttribute(inAttributeName) {
for (var n in this[conventions.PUBLISH_DIRECTIVE]) {
if (n.toLowerCase() == inAttributeName) {
return n;
}
}
};
function deserializeValue(inValue) {
switch (inValue) {
case '':
case 'true':
return true;
case 'false':
return false;
case '\\false':
return 'false';
}
return isNaN(inValue) ? inValue : parseFloat(inValue);
}
//
// automagic event mapping
//
var prefix = conventions.CUSTOM_EVENT_PREFIX;
// experimental delegating declarative event handler
// TODO(sjmiles):
// we wanted to simply look for nearest ancestor
// with a 'controller' property to be WLOG
// but we need to honor ShadowDOM, so we had to
// customize this search
var findController = function(inNode) {
// find the shadow root that contains inNode
var n = inNode.changeling || inNode;
while (n.parentNode && n.tagName !== 'SHADOW-ROOT') {
n = localParentNode(n);
}
return n.host;
};
// generic event delegate
//
// find controller nearest the event.currentTarget
// and delegate event to that controller's 'inHandlerName'
// method, if it has one
//
// can function declaratively, e.g. onclick="_('method')"
// but we bind event listeners here directly
var dispatch = function(inNode, inHandlerName, inArguments) {
if (inNode && inNode.$protected) {
log.events && console.group('[%s] dispatch [%s]', inNode.localName, inHandlerName);
inNode.$protected.dispatch(inHandlerName, inArguments);
log.events && console.groupEnd();
}
};
// automagic host-event binding
/*
var bindHostEvents = function() {
// TODO(sjmiles): must walk the prototype tree
// to bind the superset of eventDelegate maps
var p = this;
while (p) {
if (p.hasOwnProperty('eventDelegates')) {
for (var n in p.eventDelegates) {
bindHostEvent(this.node, n, p.eventDelegates[n]);
}
}
p = p.__proto__;
}
};
var bindHostEvent = function(inNode, inEventName, inHandler) {
var fn = function() {
dispatch(inNode, inHandler, [event, event.detail]);
};
// TODO(sjmiles): sadly permanent
inNode.addEventListener(inEventName, fn);
log.events && console.log('[%s] bindHostEvent: [%s] to [%s]', inNode.localName, inEventName, inHandler);
};
*/
var accumulateHostEvents = function(inEvents) {
// TODO(sjmiles): must walk the prototype tree to operate on the union of
// eventDelegates maps
var p = this;
while (p) {
if (p.hasOwnProperty('eventDelegates')) {
for (var n in p.eventDelegates) {
inEvents[n] = 1;
//bindHostEvent(this.node, n, p.eventDelegates[n]);
}
}
p = p.__proto__;
}
};
var findHostHandler = function(inEventName) {
// TODO(sjmiles): walking the tree again is inefficient; combine with code
// in accumulateHostEvents into something more sane
var p = this;
while (p) {
if (p.hasOwnProperty('eventDelegates')) {
var h = p.eventDelegates[inEventName];
if (h) {
return h;
}
}
p = p.__proto__;
}
};
//
// new experimental late bound events
//
var accumulateEvents = function(inNode, inEvents) {
var events = inEvents || {};
accumulateNodeEvents(inNode, events);
accumulateChildEvents(inNode, events);
if (inNode.tagName == 'TEMPLATE' && inNode.content) {
accumulateChildEvents(inNode.content, events);
}
return events;
};
var accumulateNodeEvents = function(inNode, inEvents) {
var a$ = inNode.attributes;
if (a$) {
for (var i=0, a; a=a$[i]; i++) {
if (a.name.slice(0, prefix.length) == prefix) {
inEvents[a.name.slice(prefix.length)] = 1;
}
}
}
};
var accumulateChildEvents = function(inNode, inEvents) {
var cn$ = localChildNodes(inNode);
if (cn$) {
for (var i=0, n; n=deref(cn$[i]); i++) {
accumulateEvents(n, inEvents);
}
}
};
function bindAccumulatedEvents(inNode, inEvents) {
var fn = __.bind(inNode);
for (var n in inEvents) {
log.events && console.log('[%s] bindAccumulatedEvents: addEventListener("%s", __)', inNode.localName, n);
inNode.addEventListener(n, fn);
}
};
// TODO(sjmiles): lots of work on the code here as we bash out a design
// we like, cruftiness increasing in the process. Will be cleaned up when
// design solidifies.
function __(inEvent) {
inEvent.on = prefix + inEvent.type;
//var on = prefix + inEvent.type;
log.events && console.group("[%s]: __ [%s]", this.localName, inEvent.on);
var t = inEvent.target;
while (t && t != this) {
t = deref(t);
var c = findController(t);
if (c == this) {
log.events && console.log('node [%s]', t.localName);
handleHostEvent.call(this, t, inEvent);
handleEvent.call(this, t, inEvent);
if (inEvent.cancelBubble) {
return;
}
}
t = t.parentNode;
}
// if we are a top-level component, we have to fire our own host events
if (t == this && !findController(t)) {
handleHostEvent.call(this, t, inEvent);
}
log.events && console.groupEnd();
};
function handleEvent(inNode, inEvent) {
if (inNode.attributes) {
var h = inNode.getAttribute(inEvent.on);
if (h) {
log.events && console.log('[%s] found handler name [%s]', this.localName, h);
dispatch(this, h, [inEvent, inEvent.detail, inNode]);
}
}
};
function handleHostEvent(inNode, inEvent) {
var h = findHostHandler.call(inNode.$protected, inEvent.type);
if (h) {
log.events && console.log('[%s] found host handler name [%s]', inNode.localName, h);
dispatch(inNode, h, [inEvent, inEvent.detail, inNode]);
}
};
</script>
</element>