Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymer 1.0 cannot find events for paper-menu or paper-item

Upgrading to Polymer 1.0, How do I listen/capture to change in "focusedItem" of iron-menu-behaviour? I cannot see any event or property change listener for an item change i.e. change in paper-item selection within a paper-menu. I cannot see any such events here: https://elements.polymer-project.org/elements/iron-menu-behavior?active=Polymer.IronMenuBehavior

like image 827
roray Avatar asked May 31 '15 13:05

roray


2 Answers

I have not been able to find any documentation on this just yet (perhaps someone else may have better luck), but the events you are looking for are iron-select and iron-deselect. Both of these events use the handler format: eventHandler(e, details), in which:

  • e is the CustomEvent.
  • details is an object with an item property pointing to the element that was selected or deselected.

I've set up a demo on Plunker that you can play around with. It has a sample menu and will log both e and details from both iron-select and iron-deselect events to the console.

That being said, however, if you are able to avoid using the event and instead use bindings, I would recommend that route first. If this is within a custom element, you could, for example, do:

<dom-module id="my-custom-element">
  <template>
    <div>
      <span>[[selectedMessage]]</span>
      <span>[[oldSelectedMessage]]</span>
    </div>
    <paper-menu selected="{{selectedIndex}}">
      <paper-item>This is item #0</paper-item>
      <paper-item>This is item #1</paper-item>
      <paper-item>This is item #3</paper-item>
    </paper-menu>
  </template>
</dom-module>

<script>
  Polymer({
    is: 'my-custom-element',
    properties: {
      selectedIndex: {
        type: Number,
        value: 0,
        observer: '_selectedIndexChanged'
      }
    },
    _selectedIndexChanged: function(newIndex, oldIndex) {
      if (typeof newIndex === 'number') {
        this.selectedMessage = 'You selected item #' + newIndex + '.';
      }
      if (typeof oldIndex === 'number') {
        this.oldSelectedMessage = 'Before, you had item #' + oldIndex + ' selected.';
      }
    }
  });
</script>
like image 182
Adaline Simonian Avatar answered Sep 24 '22 07:09

Adaline Simonian


I find that people often love to overcomplicate things when dealing with Polymer. Here's a simple approach:

JS

var menu = document.querySelector("#myMenu");
menu.addEventListener("iron-select", function(){
     console.log(menu.selected);                           // index
     console.log(menu.selectedItem.getAttribute("value")); // value
});

HTML

<paper-menu id="myMenu">
  <paper-item value="one">Foo</paper-item>
  <paper-item value="two">Bar</paper-item>
</paper-menu>
like image 21
Charles Clayton Avatar answered Sep 23 '22 07:09

Charles Clayton