我在使用递归 Polymer 组件时遇到问题,该组件具有用于将新元素插入自身的按钮。它具有用于插入元素的 add
链接。它们在单击我最初定义的元素时起作用,但对于通过添加插入的元素失败 — 我收到错误消息 Cannot read property ‘concat’ of undefined
。
要触发错误,请单击任何 add
链接,这将成功插入一个节点,然后在插入的节点上再次单击 add
。这将因错误而失败。
<script src="https://www.polymer-project.org/1.0/components/webcomponentsjs/webcomponents.min.js?20150925"></script>
<link rel="import" href="https://rawgit.com/Polymer/polymer/4c94736fac6681e84ec8c00da53484c5d3c2226b/polymer.html">
<template is="dom-bind">
<test-insert></test-insert>
</template>
<dom-module id="test-insert">
<template>
<test-recurse object="[[_object]]"></test-recurse>
</template>
</dom-module>
<dom-module id="test-recurse">
<template>
<style>
a { color: blue; text-decoration: underline; cursor: pointer; padding-left: 1em;}
</style>
Label: <span>[[object.label]]</span> <a on-click="_pushNewElement">add</a>
<ul>
<template is="dom-repeat" items="[[object.children]]">
<li><test-recurse object="[[item]]"></test-recurse></li>
</template>
</ul>
</template>
</dom-module>
<script>
(function () {
Polymer({
is: 'test-insert',
properties: {
_object: Object
},
ready: function () {
this._object = {
label: 'a1',
children: [
{ label: 'b1', children: [] },
{ label: 'b2', children: [{label: 'c1', children: []}] }
]
};
}
});
var count = 0;
Polymer({
is: 'test-recurse',
properties: {
object: Object
},
_pushNewElement: function () {
var newLabel = {label: 'Object ' + (++count)};
console.log({newLabel: newLabel}, '_pushNewElement');
this.object.children = this.object.children || [];
this.unshift('object.children', newLabel);
}
});
}());
</script>
非常感谢任何帮助!
最佳答案
你只需要修复一行:
this.set('object.children', this.object.children || []);
未正确创建 children
数组。
关于javascript - 将新子项插入递归 Polymer 组件时无法读取未定义的属性 ‘concat’,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33027577/