Mike
Mike

Reputation: 785

Trigger an event when one of a set of Polymer paper-toggle-buttons is pushed

I have a set of Polymer paper-toggle-buttons that make elements in a graph (using c3) appear and disappear. I've had some success picking up the event change with the following code:

HTML:

<div class="graph-sets-element">
    <core-label horizontal layout>
        <paper-toggle-button checked id="graph1"></paper-toggle-button>
        <h4>Graph 1</h4>
    </core-label>
</div>
<div class="graph-sets-element">
    <core-label horizontal layout>
        <paper-toggle-button checked id="graph2"></paper-toggle-button>
        <h4>Graph 2</h4>
    </core-label>
</div>

Javascript:

[].forEach.call(
    document.querySelectorAll('paper-toggle-button'), 
    function(toggle){
        toggle.addEventListener('change',function() {
            if(this.checked) {
                    chart.show('graph1');
            }
            else {
                chart.hide('graph1');
            }
        });
    }
);

The problem with my current approach is that any press of a paper-toggle-button does the same thing (hide/show the plotted graph1 line). Is there a way to grab the id of the paper-toggle-button pressed and pass it into chart.show()

Part of the challenge is that these toggle buttons are dynamically created when the user uploads new data into the graph. This means I don't necessarily know their names until the paper-toggle-button is pressed, and can't hard code each one's id.

Upvotes: 1

Views: 1790

Answers (2)

Walid Ammar
Walid Ammar

Reputation: 4126

You could access the caller element id with:

this.id

Upvotes: 3

jimi dough10
jimi dough10

Reputation: 2016

i had to do something close to this a while back maybe the approach i used will help you.

on the element you are clicking (in my case was a paper-item) assign a random attribute name (i used data) so that my element looked something like.

<paper-toggle-button on-change="{{doFunction}}" id="{{id}}"></paper-toggle-button>

then in my function i made sure to send the sender to it. that looked something like

doFunction: function (event, detail, sender) {
  var id = sender.attributes.id.value;

  // do something with the id
}

working with event listener is a little diff but similar. it would look like this

toggle.addEventListener('change', function (event) {
  var id = event.path[0].id; 

  // do something with id
});

hope that helps.

Upvotes: 1

Related Questions