聚合物模板有邮票活动吗?

Is there a stamp event for polymer templates?

每次标记其内容时,我都试图将输入元素聚焦在聚合物模板中。问题是在模板加载之前我无法 select 输入元素。目前,我只是在模板加载后 100 毫秒使用 setTimeout 来关注输入,但我想知道是否有更优雅的解决方案。此外,自动对焦属性不起作用,因为模板可能会多次取消标记和重新标记。现在,我的代码看起来像这样(这是在聚合物元素定义中):

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>

但我更喜欢这样的东西:

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>

欢迎任何想法。

有多种方法可以做到这一点,但最简单的方法是观察值,例如:

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

如果您需要跨组件通信,您还可以定义自己的事件处理程序:

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

然后您可以从任何地方使用触发事件甚至设置值,例如

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

对于 Polymer 1.0,模板在标记时会触发一个 'dom-change' 事件。但是,使用 dom-if 模板会产生显着的性能成本,因为它们需要操作 dom 树。做这样的事情会好得多:

<div id="container">
  <input id="input" hidden="[[!showInput]]" value="{{inputValue::input}}">
</div>
observers: [
  '_showInputChanged(showInput)',
],

_showInputChanged: function (showInput) {
  if (showInput) {
    this.$.input.focus();
  }
},