Vaadin组合框无法读取属性'addEventListener'为null
Vaadin ComboBox Cannot read property 'addEventListener' of null
我正在尝试添加一个事件侦听器,以显示基于在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可用。
相关文章:
- 数组在递归方法中设置为null
- 字符串在将其传递给另一个活动Android JavaScript时读取Null
- 无法获取属性'selectedIndex'的未定义引用或null引用
- Meteor方法在客户端返回null,在客户端运行的相同方法返回正确的值
- 来自文本输入null的html javascript变量
- delete在Object上效率低下,但在DOM Element's的数据属性,与null out相比
- php代码在textbox更改事件上显示null
- 相同的RegExp返回不同的结果-第一次是正确的结果,第二次是null
- 在php中提交数据时,如果某些值为null,而某些值为非null,如何进行查询
- 未捕获的类型错误:无法读取属性'addEventListener'的null chrome扩展名
- 为什么localStorage[“..”]未定义,而localStorage.getItem(“..”)为null
- ajax在输入等于null时进行检查
- html+javascript:如何在某些条件下禁用dropdownlist中的null选项
- 未捕获的类型错误:无法读取属性'状态'在react中为null
- contentWindow.document.body is null
- 在经过DATE验证的列中创建null值
- 为什么是文档.旧版应用程序中的DOM-object.properties为null
- if(foo!==null)的计算结果为true,即使foo为null
- php函数的ajax html$_POST值返回null
- ASP Page_Load元素值为null