Javascript HTML5自定义元素中的生命周期回调可以在注册后定义吗?
我最近一直在使用HTML5自定义元素,偶然发现了一个令人沮丧的问题。在所有示例中考虑以下HTML正文:Javascript HTML5自定义元素中的生命周期回调可以在注册后定义吗?,javascript,html,custom-element,Javascript,Html,Custom Element,我最近一直在使用HTML5自定义元素,偶然发现了一个令人沮丧的问题。在所有示例中考虑以下HTML正文: <body> <h2>Foo elements.</h2> <foo-element>One!</foo-element> <foo-element>Two!</foo-element> </body> 该应用程序将在Chromium版本41.0.2272.76上按预期工作
<body>
<h2>Foo elements.</h2>
<foo-element>One!</foo-element>
<foo-element>Two!</foo-element>
</body>
该应用程序将在Chromium版本41.0.2272.76上按预期工作:声明的自定义元素将触发两个回调,向控制台打印4行
[CALLBACK]创建:一个!
[回拨]附件:一!
[回调]创建:两个!
[回拨]附件:两个代码>
但现在我有了这样一个用例,我不得不将attachedCallback
的定义推迟到将来的某个场合:
var HTMLFooElement = document.registerElement('foo-element', {
prototype: Object.create(HTMLDivElement.prototype, {
createdCallback: { value: function() {
console.log('[CALLBACK] created: ', this);
}},
})
});
HTMLFooElement.prototype.attachedCallback = function() {
console.log('[CALLBACK] attached: ', this);
};
事实证明,此版本不会触发attachedCallback
,并且不会打印“附加”日志行()。此时,函数肯定会作为成员出现在我的所有自定义元素中,因为所有代码都是在处理DOM的body
部分之前执行的。不管怎样,在加载文档后在JavaScript中创建和附加新元素时,结果是一样的
注册自定义标记后生命周期回调的后期定义没有被应用,这让我感到困惑。调用registerElement
后,我应该如何定义生命周期回调并使其生效?注册元素的过程似乎在内部复制每个生命周期回调,这意味着修改原始原型不会产生任何效果。在我的项目中,我设法避免了重新定义,但是对于那些遇到同样问题的人来说,引入代理是解决问题的一种方法,它不涉及重新注册元素
var protoProxy = {
createdCallback: function(e) {
console.log('[CALLBACK] created: ', e);
},
attachedCallback: function(e) {
console.log('[CALLBACK] placeholding ...');
}
};
var HTMLFooProto = Object.create(HTMLDivElement.prototype, {
createdCallback: { value: function() {
protoProxy.createdCallback(this);
}},
attachedCallback: { value: function() {
protoProxy.attachedCallback(this);
}}
});
var HTMLFooElement = document.registerElement('foo-element', {
prototype: HTMLFooProto
});
protoProxy.attachedCallback = function(e) {
console.log('[CALLBACK] attached: ', e);
};
似乎指出需要重新注册您的元素(我甚至不确定是否可能),因为它不会自动更新。这可能是完全错误的,但符合症状。我的理解是,在调用registerement()
之前需要绑定自定义API。自v0以来,规范发生了相当大的变化(不再有document.registerement
)。当前规范明确规定,只有在定义元素时才会复制生命周期回调:
var protoProxy = {
createdCallback: function(e) {
console.log('[CALLBACK] created: ', e);
},
attachedCallback: function(e) {
console.log('[CALLBACK] placeholding ...');
}
};
var HTMLFooProto = Object.create(HTMLDivElement.prototype, {
createdCallback: { value: function() {
protoProxy.createdCallback(this);
}},
attachedCallback: { value: function() {
protoProxy.attachedCallback(this);
}}
});
var HTMLFooElement = document.registerElement('foo-element', {
prototype: HTMLFooProto
});
protoProxy.attachedCallback = function(e) {
console.log('[CALLBACK] attached: ', e);
};