user3916009
user3916009

Reputation: 193

Can I select any element in the document using Polymer's Automatic Node Finding?

I am working on a Polymer project and I a few custom elements nested. For example, I have a custom element called <example-main>. Suppose that this element has a function called displayMessage()

I have another custom element defined inside <example-main> called <example-alerts>. I want the alerts element to be able to use the function in its parent, main, to display a message.

To achieve this, I am trying to select the element <example-main id='mainEl'> by using the Polymer's Automatic Node Finding hash, this.$.mainEl and using the function like so: this.$.mainEl.displayMessage();

However, I get this error message:

Uncaught TypeError: Cannot read property 'displayMessage' of undefined

Am I making a wrong approach of having Polymer elements call functions in other Polymer objects?

To visualize things a little better, the index.html would look something like:

...

<body>
  <example-main id='mainEl'></example-main>
</body>

...

while example-main.html looks something like:

<polymer-element name='example-main'>
<template>
  ...

  <example-alerts>
</template>
<script>
  Polymer(example-element, {
    displayMessage: function(){
        //do message showing magic
    }
  });
</script>
</polymer-element>

and lastly, example-alerts.html looking like:

<polymer-element name='example-alerts'>
<template>
  ...
    <paper-button on-tap='{{callFunction}}'></button>

</template>
<script>
  Polymer(example-alerts, {
    callFunction: function(){
        //call the function in parent
        this.$.mainEl.displayMessage();
    }
  });
</script>
</polymer-element>

Upvotes: 0

Views: 266

Answers (1)

Ajay Singh Beniwal
Ajay Singh Beniwal

Reputation: 19037

You are not doing this correct way , you cannot find nodes this way . Node finding just search within same element defined in elements outermost template.

You should either change your approach or you can use events to handle the situation pls see the sample demo which can work for you.

<polymer-element name='example-alerts'>
<template>
  ...
    <paper-button on-tap='{{callFunction}}'></button>

</template>
<script>
  Polymer(example-alerts, {
    callFunction: function(){
        //call the function in parent
 this.fire('ouch', {msg: 'That hurt!'}); 
    }
  });
</script>
</polymer-element>


--Second Element

<polymer-element name='example-main'>
<template>
  ...

  <example-alerts on-ouch='{{displayMessage}}'>
</template>
<script>
  Polymer(example-element, {
    displayMessage: function(){
        //do message showing magic
    }
  });
</script>
</polymer-element>

Upvotes: 3

Related Questions