最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Listening global window events in stencilJS - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

3 Answers 3

Reset to default 4

I 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) {})
发布评论

评论列表(0)

  1. 暂无评论