Is there a stamp event for polymer templates?

匿名 (未验证) 提交于 2019-12-03 01:20:02

问题:

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>

Any ideas are appreciated.

回答1:

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();   } },


回答2:

There are multiple ways to do this, but the easiest would to observe the value, e.g.:

// you already have an Id assigned to the input, so you can use that reference. ..   showInputChanged: function() {   this.$.input.focus();  } ..

You can also define your own event handlers if you need cross component communication:

..  ready: function() {   this.addEventListener("on-stamp", function(e) {    if(e.detail.value != undefined) this.$.input.value = e.detail.value;     this.$.input.focus();     });  } ..

Then you can use fire an event from anywhere and even set the value, e.g.

   setValue: function(s) {     this.fire("on-stamp", {value: s});    },


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!