聚合物 - 从if模板中选择DOM元素

时间:2015-11-14 15:38:46

标签: polymer

我正在学习聚合物。我的视图设置如下:

我-view.html

<dom-module id="my-view">   
  <template>
    <template is="dom-if" if="[[ areAvailable ]]">
      <my-component id="myComponent"></my-component>
      <button type="button" on-click="onButtonClick">Test</button>
    </template>

    <template is="dom-if" if="[[ !areAvailable ]]">
      <div>Move along</div>
    <template>
  </template>

  <script>
    Polymer({
      is:'my-view',
      properties: {
        areAvailable: Boolean
      },

      onButtonClick: function() {
        this.$.myComponent.test();
      }
    });
  </script>
</dom-module>

此视图根据my-component标记显示areAvailable。如果用户点击了&#34;测试&#34;按钮,我需要在my-component中执行一个功能。 my-component设置如下:

我-component.html

<dom-module id="my-component">  
  <template>
    <h1>hello there!</h1>
  </template>

  <script>
    Polymer({
      is:'my-component',    
      test: function() {
        alert('voila!');
      }
    });
  </script>
</dom-module>

我的挑战是,我的方法 IF my-component 在&#34; if&#34;模板。当my-component位于&#34; if&#34;模板,我收到一条错误消息:

TypeError: Cannot read property 'test' of undefined

我做错了什么?

2 个答案:

答案 0 :(得分:2)

  

注意:使用数据绑定动态创建的节点(包括dom-repeatdom-if模板中的节点)不会添加到this.$哈希中。哈希仅包含静态创建的本地DOM节点(即元素最外层模板中定义的节点)。

来源:https://www.polymer-project.org/1.0/docs/devguide/local-dom.html#node-finding

由于您已经为按钮上的click事件添加了一个侦听器,因此可以像这样重新定义该侦听器:

Polymer({
  ...
  onButtonClick: function() {
    // The this.root here refers to the local dom
    // It is highly advised that you use Polymer.dom(<node>) when doing dom manipulations
    Polymer.dom(this.root).querySelector('#myComponent').test(); 
  }
});

答案 1 :(得分:1)

聚合物具有这个简单的功能......

this.$$('#myComponent')

https://www.polymer-project.org/1.0/docs/devguide/local-dom#node-finding

相关问题