简体   繁体   English

如何正确使用铁选? 像铁页一样使用时,项目似乎为空

[英]How to use iron-selectable correctly? Items appear to be null when used like iron-pages

I have a fairly simple Polymer element which implements IronSelectableBehavior but I find that this.items is always an empty array. 我有一个相当简单的Polymer元素,它实现IronSelectableBehavior但我发现this.items始终是一个空数组。

I have it setup the same way iron-pages is, simply with child elements and not much else: 我用iron-pages设置方式相同,只是带有子元素,没有太多其他内容:

<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/iron-selector/iron-selectable.html">
<dom-module id="test">
    <template>
        <style>
        </style>
        <div id="container">
            <content></content>
        </div>
    </template>
    <script>
    (function(root) {
        'use strict';

        Polymer({
            is: 'test',

            behaviors: [Polymer.IronSelectableBehavior],

            observers: [
                '_selectedChanged(selected)'
            ],

            _selectedChanged: function(val, prev) {
                var self = this,
                    selected = this._valueToItem(val);

                if(!selected) {
                    throw val.toString() + ' not found.';
                }
            }
        });
    })(window);
    </script>
</dom-module>

With the following example: 用下面的例子:

<test attr-for-selected="data-test" selected="{{selected}}">
    <div data-test="one"></div>
    <div data-test="two"></div>
</test>

When _selectedChanged is called, selected is undefined because this.items is an empty array. 调用_selectedChangedselectedundefined因为this.items是一个空数组。

iron-pages is setup with even less code than this but somehow works, so I'm unsure what is wrong here. iron-pages设置的代码比这更少,但是以某种方式起作用,所以我不确定这里出了什么问题。

The reason for this behaviour is fairly simple: 此行为的原因非常简单:

  • iron-selectable sets this.items to the content nodes after attachment iron-selectablethis.items设置为附加后的内容节点
  • It does this by observing selected and populating this.items if they are not already 它通过观察selected并填充this.items如果尚未添加)来实现

This causes issues if you want to interact with this.items in your own selected observer, simply because the array is not yet populated by the time your observer is executed. 如果要在自己selected观察器中与this.items交互, this.items导致问题,这仅仅是因为在执行观察器时尚未填充数组。

To get around this, listen on the iron-select event which is guaranteed to execute after the iron-selectable observer. 要解决此问题,请侦听iron-select事件,该事件一定会 iron-selectable观察器之后执行。

If you need to know the previous value (because iron-select doesn't get it passed), set it in a selected observer and read it in your event listener. 如果您需要知道先前的值(因为iron-select无法通过它),请在selected观察器中进行设置,然后在事件侦听器中读取它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM