Polymer:如何在条件模板下向自定义聚合物元素添加事件侦听器

编程入门 行业动态 更新时间:2024-10-27 22:33:10
本文介绍了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.$.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:如何在条件模板下向自定义聚合物元素添加事件侦听器

本文发布于:2023-08-03 08:01:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1285452.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:侦听器   聚合物   自定义   元素   模板

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!