Let's say that I have something like this somewhere in application:
var event = new Event('build');
window.dispatchEvent(event);
In stencilJS documentation, they say that you can listen to global events like this:
@Listen('body:scroll')
handleScroll(ev) {
console.log('the body was scrolled', ev);
}
But I couldn't find way to listen to event that is emitted on window, like I can listen it with plain Javascript:
window.addEventListener('build', function (e) {
console.log('Event happened',e);
}, false);
Any ideas?
Let's say that I have something like this somewhere in application:
var event = new Event('build');
window.dispatchEvent(event);
In stencilJS documentation, they say that you can listen to global events like this:
@Listen('body:scroll')
handleScroll(ev) {
console.log('the body was scrolled', ev);
}
But I couldn't find way to listen to event that is emitted on window, like I can listen it with plain Javascript:
window.addEventListener('build', function (e) {
console.log('Event happened',e);
}, false);
Any ideas?
Share Improve this question edited Nov 2, 2019 at 21:51 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Nov 20, 2017 at 16:57 Dragan MalinovicDragan Malinovic 6026 silver badges13 bronze badges3 Answers
Reset to default 4I tried the stencil docs example and it did not work. I then changed the 'body' to 'window' and now I see the scroll event in the console.
@Listen('window:scroll')
handleScroll(ev) {
console.log('the body was scrolled', ev);
}
import { Listen } from '@stencil/core';
@Listen('scroll', { target: 'window' })
handleScroll(ev) {
console.log('the body was scrolled', ev);
}
Official documentation : https://stenciljs./docs/events
Ok, so i did a example of listening to a ponents published event in this blog post.
But here is the general solution. I would use Stencils Event Emitter and emit from a ponent. Lets say you do this and emit an event from your ponent called fancyEvent...
@Event() fancyEvent: EventEmitter;
...
this.fancyEvent.emit($event);
To listen to this event on the window (i.e. in index.js), you can do one of two things. If you have a transpiler such as typescript, you can listen like this
@Listen('fancyEvent')
function doSomethingFancy() {}
But in vanilla es5 style javascript you can also listen to these custom events like this.
window.addEventListener('fancyEvent', function(e) {})