Polymer:如何在条件模板下向自定义聚合物元素添加事件侦听器 [英] Polymer: How to add event listeners to custom polymer element under conditional template

查看:64
本文介绍了Polymer:如何在条件模板下向自定义聚合物元素添加事件侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义元素 它会触发一个事件 'item-selected'我在另一个自定义元素中使用此元素,当我尝试将事件侦听器添加到此元素时

I have a custom element <y-list> which fires an event 'item-selected' i am using this element in another custom element and when i try to add eventlistener to this element

<dom-module id="my-list">
 <template is="dom-if" if="{{show}}">
    <y-list list="{{list}}">
    </y-list>
    <hr>
 </template>
</dom-module>

Polymer({

is: 'my-list',

properties: {

  show: {
    type:Boolean,
    value:function() {
        return false
    }
  },
  list: {
    type:Array,
    value:[]
  }
},
ready: function(){
},
attached: function(){
   this.querySelector('y-list').addEventListener('item-selected', function(e){
   console.log(e.detail);
}   
});

我收到错误无法读取 null 的属性addEventListener"

但是如果我删除 dom-if 条件或使用 hidden$ 我能够找到元素并添加事件侦听器并收听 item-selected 事件

but if i remove dom-if condition or use hidden$ i am able to find the element and add the eventlistener and listen to item-selected event

我知道attached在ready后被调用,所以我在attached中添加事件监听器,但即使我将show属性设置为true,我也无法找到该元素对于

I know that attached is called after ready so i am adding event listener in attached but i am unable to find the element even if i set the show attribute to true for <my-list>

推荐答案

dom-if的表达式为false时,内容不存在.在这种情况下,最好将 show 绑定到一个类以使用 CSS 隐藏内容而不是删除它.隐藏的内容存在并且可以使用 this.$this.$$

When the expression of the dom-if is false the content doesn't exist. In this case it works better to bind show to a class to hide the content usin CSS instead of removing it. Hidden content exists and can be accessed using this.$ or this.$$

this.querySelector('y-list') 在 light DOM 中选择元素(使用 投影).无论如何最好使用 Polymer.dom(this).querySelector() .

this.querySelector('y-list') selects elements in the light DOM (projected using <content>). It's better to use Polymer.dom(this).querySelector() anyway.

要从元素模板中选择使用 this.$.someIdthis.$$('some-selector')Polymer.dom(this.root).querySelector()

To select from the elements template use this.$.someId, this.$$('some-selector') or Polymer.dom(this.root).querySelector ()

这篇关于Polymer:如何在条件模板下向自定义聚合物元素添加事件侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆