Reputation: 489
From the Polymer Starter Kit prototype, I have a function from <my-view1>
, which fires a function from the <my-app>
through an event listener.
I want to be able to send some info along with that, so I have set up a data attribute which is captured in a variable.
How can I then send that variable to my main event listener and function in <my-app>
?
<my-view1>
Data attribute:
<paper-button raised on-tap="open" data-target="#dialog">Dialog</paper-button>
<my-view1>
Function:
open: function(e) {
const target = e.target.dataset.target || e.target.parentElement.dataset.target;
this.fire('open-dialog'); //send target variable somehow?
}
<my-app>
listener:
listeners: {
'open-dialog': 'handleOpenDialog' //get target variable from my-view1
}
<my-app>
Function:
handleOpenDialog: function(e) {
console.log(target); //get target variable from listener
}
Thanks!
Upvotes: 1
Views: 833
Reputation: 138376
You could specify the event detail when calling fire(eventName, [detail], [options])
. In your case, you'd pass target
(the selector for the target dialog) in the event detail, and your event handler would query its children with that selector to fetch the dialog.
// my-view1
open: function(e) {
const target = e.target.dataset.target;
this.fire('open-dialog', target);
}
// my-app
handleOpenDialog: function(e) {
const target = e.detail;
const dialog = this.$$(target);
if (dialog) {
dialog.opened = true;
}
}
HTMLImports.whenReady(() => {
Polymer({
is: 'my-app',
listeners: {
'open-dialog': 'handleOpenDialog'
},
handleOpenDialog: function(e) {
const target = e.detail;
const dialog = this.$$(target);
if (dialog) {
dialog.opened = true;
}
}
});
Polymer({
is: 'my-view1',
open: function(e) {
const target = e.target.dataset.target;
this.fire('open-dialog', target);
}
});
});
<head>
<base href="https://polygit.org/polymer+1.7.0/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="paper-button/paper-button.html">
<link rel="import" href="paper-dialog/paper-dialog.html">
</head>
<body>
<my-app>
<my-view1></my-view1>
</my-app>
<dom-module id="my-app">
<template>
<content></content>
<paper-dialog id="dialog1">
<h2>Dialog 1</h2>
<div class="buttons">
<paper-button dialog-dismiss>Cancel</paper-button>
<paper-button dialog-confirm autofocus>Accept</paper-button>
</div>
</paper-dialog>
<paper-dialog id="dialog2">
<h2>Dialog 2</h2>
<div class="buttons">
<paper-button dialog-dismiss>Cancel</paper-button>
<paper-button dialog-confirm autofocus>Accept</paper-button>
</div>
</paper-dialog>
</template>
</dom-module>
<dom-module id="my-view1">
<template>
<paper-button on-tap="open" data-target="#dialog1">Dialog 1</paper-button>
<paper-button on-tap="open" data-target="#dialog2">Dialog 2</paper-button>
</template>
</dom-module>
</body>
Upvotes: 1