是否有聚合物模板的印章事件? [英] Is there a stamp event for polymer templates?
问题描述
我试图在每次标记其内容时将输入元素聚焦在聚合物模板内。问题是在模板加载之前我无法选择输入元素。目前,我只是在模板加载后使用setTimeout来聚焦输入100ms,但我想知道是否有更优雅的解决方案。此外,自动聚焦属性不起作用,因为模板可能会多次取消标记和重新标记。现在,我的代码看起来像这样(这是在聚合物元素定义中):
I am trying to focus an input element inside of a polymer template every time it stamps its contents. The problem is that I cannot select the input element until the template has loaded. Currently, I am just using setTimeout to focus the input 100ms after the template should load, but I want to know if there is a more elegant solution. Also, the autofocus attribute doesn't work, because the template may un-stamp and re-stamp many times. Right now, my code looks something like this (this is inside a polymer element definition):
Polymer({
// ...
showInput: false,
makeInputVisible: function() {
this.showInput = true;
var container = this.$.container;
setTimeout(function() {
container.querySelector("#input").focus();
}, 100);
},
});
<div id="container">
<template if="{{showInput}}">
<input id="input" is="core-input" committedValue="{{inputValue}}" />
</template>
</div>
但我更喜欢这样的东西:
But I would prefer something more like this:
Polymer({
// ...
showInput: false,
makeInputVisible: function() {
this.showInput = true;
},
focusInput: function() {
this.$.container.querySelector("#input").focus();
},
});
<div id="container">
<template if="{{showInput}}"
on-stamp="{{focusInput}}">
<input id="input" is="core-input" committedValue="{{inputValue}}" />
</template>
</div>
任何想法都表示赞赏。
推荐答案
使用Polymer 1.0,模板在标记时会触发dom-change事件。但是,使用dom-if模板会产生显着的性能成本,因为它们需要操作dom树。做这样的事情要好得多:
With Polymer 1.0, there is a 'dom-change' event fired by templates when they stamp. However, there is a significant performance cost to using dom-if templates since they need to manipulate the dom tree. It would be much better to do something like this:
<div id="container">
<input id="input" hidden="[[!showInput]]" value="{{inputValue::input}}">
</div>
observers: [
'_showInputChanged(showInput)',
],
_showInputChanged: function (showInput) {
if (showInput) {
this.$.input.focus();
}
},
这篇关于是否有聚合物模板的印章事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!