routing events with Polymer

I'm trying to wrap a button using polymer.

HTML:

<polymer-element name="sp-button" attributes="active">
  <template>
    <link rel="stylesheet" href="sp-button.css">
    <button type="button"><content></content></button>
  </template>
  <script src="sp-button.js"></script>
</polymer-element>

JS:

Polymer('sp-button', {
  active: false,
  activeChanged: function() {
    console.log('active ' + this.active);
  }
});

I'm not sure how to allow user of that polymer element to listen to click events or hover events. Also, in the case where two buttons are wrapped in that polymer element.

Upvotes: 4

Views: 3034

Answers (3)

Tink
Tink

Reputation: 31

You'd probably want to stop the propagation of the click event if you were going to catch it and dispatch something new.

Upvotes: 0

CletusW
CletusW

Reputation: 3980

The two-button case would look something like this:

<polymer-element name="sp-button" attributes="active">
  <template>
    <link rel="stylesheet" href="sp-button.css">
    <button type="button" on-click="onSendClick">Send</button>
    <button type="button" on-click="onReceiveClick">Receive</button>
  </template>
  <script src="sp-button.js"></script>
</polymer-element>

JS:

Polymer('sp-button', {
  //...
  onSendClick: function() {
    this.fire('send');
  },
  onReceiveClick: function() {
    this.fire('receive');
  }
});

And then you could listen for those domain-specific events from the outside using addEventListener:

var button = document.querySelector('sp-button');
button.addEventListener('send', function(e) {
  //...
});
button.addEventListener('receive', function(e) {
  //...
});

The benefit to this method is that it hides away the implementation detail that the user clicked a button to cause the send event to occur. As far as the user of the sp-button element is concerned, it could have been a button click, a dropdown selection, a mouse hover, or any number of things that caused it. All the user cares about is your public API: that your element will fire a send event and a receive event when it wants the outside world to take those respective actions.

Upvotes: 0

ebidel
ebidel

Reputation: 24109

Users of your element can setup listeners like any normal HTML elements:

var button = document.querySelector('sp-button');
button.addEventListener('click', function(e) {
  alert('from outside');
});                          

In a polymer-element, you can also capture the click event on the button using on-click, do something interesting with it, and/or fire another event:

<button on-click="clickHandler"><content>Button text</content></button>
...
clickHandler: function(e, detail, sender) {
  alert('from inside'); 
  this.fire('insideclick', {msg: 'from inside'});
}

Full demo: http://jsbin.com/uqubAGO/1/edit

Upvotes: 4

Related Questions