Matan Gubkin
Matan Gubkin

Reputation: 3199

How to call a function from inside nested components

I have this code in index.html:

<core-pages selected="{{welcomPage}}">
  <div class="blueBackground">
    <h1>asd</h1>
    <h3>asd</h3>
    <paper-button on-tap="{{welcomPagePlus}}">
      Keep Going
      <core-icon icon="forward"></core-icon>
    </paper-button>
  </div>
  <div>welcom 2</div>
</core-pages>

and I want to call a function when the user clicks the button. I have tried this in my app.js:

function welcomPagePlus() {
    ...   
}

this polymer code is locate in my primary file so I can't use the Polymer({...}) function. Also the button is deep inside my shadow-dom so it looks like that is the problem. Please help me find how to call a function from the shadow-dom

Upvotes: 0

Views: 537

Answers (2)

Erik Isaksen
Erik Isaksen

Reputation: 226

You can also do it this way. Although sometimes it's useful, I hate piercing shadow boundaries and I avoid it if I can.

Codepen example

<link rel="import" href="https://www.polymer-project.org/0.5/components/core-pages/core-pages.html">
<link rel="import" href="https://www.polymer-project.org/0.5/components/core-icon/core-icon.html">
<link rel="import" href="https://www.polymer-project.org/0.5/components/paper-button/paper-button.html">
<link rel="import" href="https://www.polymer-project.org/0.5/components/core-icons/core-icons.html">

<paper-button>
  Keep Going
  <core-icon icon="forward"></core-icon>
</paper-button>

<core-pages selected="second">
  <div name="first" class="blueBackground">
    <h1>asd</h1>
    <h3>asd</h3>   
  </div>
  <div name="second">welcome 2</div>
</core-pages>

JavaScript in the Light DOM

document.querySelector('paper-button').addEventListener('click', function(e){
  var currentPage = document.querySelector('core-pages');
  currentPage.selected = currentPage.selected == 0 ? 1 : 0;
});

Upvotes: 1

Mathias Vonende
Mathias Vonende

Reputation: 1380

You can access shadow-dom elements from the "outside" like this:

First: Give your paper-button an id-Attribute: <paper-button id="paper-button-id" ...>

var button = document.querySelector("core-pages")
    .shadowRoot
    .querySelector("#paper-button-id");

There is no polymer required for this code. Be aware, that the 'shadowRoot' and 'querySelector' methods may not work in every browser. There may be better solutions, using polymer-methods.

Upvotes: 2

Related Questions