方式一:
<dom-module id="x-custom">
<template>
<div>I will respond</div>
<div>to a tap on</div>
<div>any of my children!</div>
<div id="special">I am special!</div>
</template>
<script>
Polymer({
is: 'x-custom',
listeners: {
'tap': 'regularTap',
'special.tap': 'specialTap',//special为元素的id,tap为事件名称。语法格式为:nodeId.eventName
},
regularTap: function(e) {
alert("Thank you for tapping");
},
specialTap: function(e) {
alert("It was special tapping");
}
});
</script>
</dom-module>
方式二:
this.listen(this.$.myButton, 'tap', 'onTap');
this.unlisten(this.$.myButton, 'tap', 'onTap');
方式三:
To fire a custom event from the host element use the fire
method. You can also pass in data to event handlers as an argument to fire
.
<dom-module id="x-custom">
<template>
<button on-click="handleClick">Kick Me</button>
</template>
<script>
Polymer({
is: 'x-custom',
handleClick: function(e, detail) {
this.fire('kick', {kicked: true});
}
});
</script>
</dom-module>
<x-custom></x-custom>
<script>
document.querySelector('x-custom').addEventListener('kick', function (e) {
console.log(e.detail.kicked); // true
})
</script>
Use Polymer.dom(event)
to get a normalized event object that provides equivalent target data on both shady DOM and shadow DOM. Specifically, the normalized event has the following properties:
-
rootTarget
: The original or root target before shadow retargeting (equivalent toevent.path[0]
under shadow DOM orevent.target
under shady DOM). -
localTarget
: Retargeted event target (equivalent toevent.target
under shadow DOM). This node is always in the same scope as the node where the listener was added. -
path
: Array of nodes through which event will pass (equivalent toevent.path
under shadow DOM).
Example:
<!-- event-retargeting.html -->
...
<dom-module id="event-retargeting">
<template>
<button id="myButton">Click Me</button>
</template>
<script>
Polymer({
is: 'event-retargeting',
listeners: {
'click': 'handleClick',
},
handleClick: function(e) {
console.info(e.target.id + ' was clicked.');
}
});
</script>
</dom-module>
<!-- index.html -->
...
<event-retargeting></event-retargeting>
<script>
var el = document.querySelector('event-retargeting');
el.addEventListener('click', function(){
var normalizedEvent = Polymer.dom(event);
// logs #myButton
console.info('rootTarget is:', normalizedEvent.rootTarget);
// logs the instance of event-targeting that hosts #myButton
console.info('localTarget is:', normalizedEvent.localTarget);
// logs [#myButton, document-fragment, event-retargeting,
// body, html, document, Window]
console.info('path is:', normalizedEvent.path);
});
</script>