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

寵の児 提交于 2019-12-11 10:16:40

问题


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.


回答1:


You could access the caller element id with:

this.id




回答2:


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.



来源:https://stackoverflow.com/questions/27682028/trigger-an-event-when-one-of-a-set-of-polymer-paper-toggle-buttons-is-pushed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!