Polymer:如何在条件模板下向自定义聚合物元素添加事件侦听器 [英] Polymer: How to add event listeners to custom polymer element under conditional template
问题描述
我有一个自定义元素
它会触发一个事件 '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.$.someId
、this.$$('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屋!