自定义事件
你也可以触发自己的事件,然后从 HTML 页面的 Polymer 元素中侦听它们
此 Element 触发自定义事件
<dom-module id="custom-event">
<template>
<style>
#inner{
width: 200px;
height: 50px;
border: 1px solid blue;
margin-top: 15px;
}
</style>
<div id="inner" on-tap="firing">I'll fire a custom event</div>
</template>
</dom-module>
<script>
Polymer({
is:'custom-event',
firing:function(){
this.fire('my-event',{value:"Yeah! i'm being listened"}) //fire is the method which is use to fire custom events, second parameter can also be null if no data is required
}
})
</script>
这是一个正在侦听该自定义事件的元素
<link rel="import" href="custom-event.html">
<dom-module id="custom-event-listener">
<template>
<style></style>
<custom-event on-my-event="_myListen"></custom-event>
</template>
</dom-module>
<script>
Polymer({
is:'custom-event-listener',
/* listeners:{ //you can also use listener object instead of on-event attribute
'my-event':'listen'
},*/
_myListen:function(e,detail){
alert(detail.value+"from Polymer Element");
},
})
</script>
从 HTML 听
<html>
<head>
<meta charset="UTF-8">
<title>Events</title>
<script src='bower_components/webcomponentsjs/webcomponents-lite.min.js'></script>
<link rel="import" href="./bower_components/polymer/polymer.html">
<link rel="import" href="custom-event-listener.html">
</head>
<body>
<!--As event bubbles by default we can also listen to event from custom-event-listener instead of custom-event-->
<custom-event-listener></custom-event-listener>
</body>
<script>
document.querySelector('custom-event-listener').addEventListener('my-event',function(e){
console.log(e);
alert(e.detail.value+"from HTML");
})
</script>
</html>