Vaadin组合框无法读取属性'addEventListener'为null

Vaadin ComboBox Cannot read property 'addEventListener' of null

本文关键字:null addEventListener 属性 组合 读取 Vaadin      更新时间:2023-09-26

我正在尝试添加一个事件侦听器,以显示基于在Vaadin组合框中选择的模式的图像。要做到这一点,我希望有一个事件监听器。。。更改ComboBox值后,在JSON文件中查找图像的路径,并在div占位符上显示所选图像。

我还没有构建到那个级别的解决方案,因为我的查询选择器有问题。据我所知,它无法创建变量"combobox",因此事件处理程序不会添加到"comboox"中,因为它不存在。

加载页面输出的错误为:

Uncaught TypeError: Cannot read property 'addEventListener' of null

项目代码为:

<div id="patternSelect">
            <template is="dom-bind" id="paver">
              <div class="fieldset">
                <vaadin-combo-box id="cb1" label="Pattern" class="patterns" items="[[patterns]]"></vaadin-combo-box>
                <br>
                <vaadin-combo-box id="cb2" label="Color" class="colors" items="[[colors]]"></vaadin-combo-box>
              </div>
            </template>
        </div>

<script type="text/javascript">
    $( document ).ready(function() {
            var combobox = document.querySelector('#cb1');
            combobox.addEventListener('value-changed', function(event) {
              console.log(event.detail.value);
            });
            combobox.addEventListener('selected-item-changed', function(event) {
              console.log(event.detail.value);
        });
    });
</script>

由于组合框嵌套在template标记中:

<template is="dom-bind" id="paver">

该模板的内容在激活并添加到DOM之前是不可访问的,请参阅本教程。

Vaadin/Polymer会在加载时查看这些模板并激活它们,因此当您运行代码时,它看起来好像这个操作还没有完成——导致您的document.querySelector('#cb1')返回null

一个粗略的解决方案是在超时时包装侦听器代码,然后一切正常:

$( document ).ready(function() {
       addListenersDelayed()
    });
});
function  addListenersDelayed(){
    setTimeout( function(){
        addListeners();
    }, 1000)    
};  
function addListeners(){
    combobox.addEventListener('value-changed', function(event) {
        console.log(event.detail.value);
    });
    combobox.addEventListener('selected-item-changed', function(event) {
        console.log(event.detail.value);
    });
}

另一种方法是使用聚合物生活方式回调:

// select your template
var paver = document.querySelector('#paver');
// define the ready function callback
paver.ready = function () {
    // use the async method to make sure you can access parent/siblings
    this.async(function() {
    // access sibling or parent elements here
        var combobox = document.querySelector('#cb1')
        combobox.addEventListener('value-changed', function(event) {
            console.log(event.detail.value);
        });
        combobox.addEventListener('selected-item-changed', function(event) {
            console.log(event.detail.value);
        });
    });
};

这种方法的危险在于,在注册回调之前,组件就已经准备好了。从本质上讲,这两种方法都确保在执行代码时模板的DOM可用。