Search code examples
javascriptpolymerweb-component

paper-radio-group-changed not firing when a radio button is selected by script


I have a paper-radio-group that listens to event paper-radio-group-changed. This event fires perfectly when someone manually click the radio button, but it does not fire when it is assigned by script. Here is how I assign it by script

<paper-radio-group id="prg">
    <paper-radio-button name="a">A</paper-radio-button>
    <paper-radio-button name="b">B</paper-radio-button>
    <paper-radio-button name="c">C</paper-radio-button>
</paper-radio-group>

...
<script>
    $("#prg").selected = "a";
    $(document).on('paper-radio-group-changed', '#prg', {}, function (e) {
      //Whatever here is not executed
    });
</script>

More observations:

The radio button "a" is actually get selected. But the event is never fired. Why? Did I choose the wrong event listener or need additional event listener?


Solution

  • paper-radio-group-changed is fired when a selection change happens through the method select(itemName):

    // paper-radio-group-changed
    
    let prg = document.querySelector('#prg');
    
    prg.select('b');
    
    prg.addEventListener('paper-radio-group-changed', e => {
        alert('paper-radio-group-changed');
    });
    // jQuery on() works as well
    

    Listening to changes in the selected attribute is possible by using Polymer.IronSelectableBehavior's selected-changed event:

    // selected-changed
    
    prg.selected = 'b';
    
    prg.addEventListener('selected-changed', e => {
        alert('selected-changed');
    });
    

    Find more information on paper-radio-group and its events here.

    Two notes on jQuery + Polymer

    Elements in the Shadow DOM are not so easy to select with jQuery Using jQuery with shadow dom.

    Setting custom attributes with jQuery don't always behave how Polymer expects:

    $('#prg').attr({foo: 'bar'}); // These syntaxes should work
    $('#prg').attr('foo': 'bar');
    // However for the attribute 'selected', being a valid HTML 
    // attribute which accepts a true/false (set/undefined) value pair,
    // the value is ingored by jQuery resulting in selected="selected"
    $('#prg').attr('selected', 'b');
    

    so selecting with document.querySelector() is probably safer in this case.

    Note that if you place <paper-radio-group id="prg"> inside of another polymer element (i.e. <my-app></my-app>) you can access it using this.$:

    class MyApp extends Polymer.Element {
      static get is() { return  'my-app' }
      ready() {
        super.ready();
        this.$.prg.selected = 'b';
      }
    }
    

    https://www.polymer-project.org/2.0/docs/devguide/dom-template#node-finding