在Polymer dom-repeat内部定位元素

时间:2016-02-05 09:35:01

标签: javascript polymer web-component

我正在使用Polymer 1.0,我正试图从下面的模板中的脚本访问items

我花了一段时间用这个,我只是无法弄清楚这个模板的范围,如何访问'my-swiper-icon'元素。

简而言之,我如何找到“#slide_n #item_m”?该路径不适用于查询选择器。为了完整性#slide_n确实有效,但是它有一个#document_fragment子项,所以没用...对吗?

<dom-module id="my-swiper">
  <template>
    <style include="my-swiper-import">
      :host {
        display: block;
      }
    </style>

    <!-- Swiper -->
    <div class="swiper-container">
        <div class="swiper-wrapper">
          <template id="slides_template" is="dom-repeat" items="{{slides}}">
            <div class="swiper-slide" id="slide_{{index}}">
              <div>
                <template id="items_template" is="dom-repeat" items="{{item.items}}">
                  <my-swiper-icon id="item_{{index}}" data="{{item}}"/>
                </template>
              <div>
            </div>
          </template>
        </div>
        <!-- Add Pagination -->
        <div class="swiper-pagination"></div>
        <!-- Add Arrows -->
        <div class="swiper-button-next"></div>
        <div class="swiper-button-prev"></div>
    </div>

  </template>
  <script>
    (function() {
      'use strict';

      Polymer({
        is: "my-swiper",

        properties: {
          slides: {
            type: Array,
            value: [],
            notify: true,
            observer: '_slidesChanged'
          }
        },

        listeners: {
          'tap': '__tap',
          'resize': '__resized'
        },

        __tap: function(e) {    
          //
        },

        __resized: function(e) {
          // How do I locate "#slide_n #item_m" ????
        },

        _slidesChanged: function(newValue, oldValue) {
          //
        },

        ready: function() {
          this.slides = [                
            {
              items: [
                { hash: 'foobar' },
                { hash: 'foobar' },
                { hash: 'foobar' },
                { hash: 'foobar' }
              ]
            },
            {
              items: [
                { hash: 'barfoo' },
                { hash: 'barfoo' }
              ]
            }
          ];
        },

        attached: function() {
          this.async(function() {
            var swiper = new Swiper('.swiper-container', {
              pagination: '.swiper-pagination',
              paginationClickable: '.swiper-pagination',
              nextButton: '.swiper-button-next',
              prevButton: '.swiper-button-prev',
              spaceBetween: 30,
              hashnav: true
            });
            this.__resized(null);
            window.addEventListener("resize", this.__resized.bind(this));
          });
        }

      });

    })();
  </script>

</dom-module>

1 个答案:

答案 0 :(得分:1)

Polymer提供this$.someId简写来访问元素的本地DOM中的元素,但这不适用于动态创建的元素(例如在template="dom-if"template="dom-repeat"内或appendNode(),... 对于动态创建的节点,请改用Polymer.dom(this.root).querySelectorAll(selector)