cujojs / most

Ultra-high performance reactive programming
MIT License
3.49k stars 231 forks source link

RemoveEventListener when using fromEvent #518

Closed edkongz closed 6 years ago

edkongz commented 6 years ago

Summary

I can't work this out for the life of me. I know this is not the recommended way but how can you remove the listener when using fromEvent?

I know this has been covered regarding DOM elements.

How do you remove an event listener for the window object? Or what is the best way to listen to a window event?

fromEvent("resize", window)
  .forEach(console.log)

How do I remove this event listener?

davidchase commented 6 years ago

hi @kongdigital have you tried slice, take, takeWhile, until, etc? check out the API info about slicing streams here

for example from the docs you observe all the mouse events from the resize of the window until you click on the document at that point dispose is called and removeEventListener on the resize event

fromEvent('resize', window)
    .until(fromEvent('click', document))
    .observe(mouseEvent => console.log(mouseEvent));

You can even create your own operator that calls dispose of the source stream in this case fromEvent and you can removeEventlistener from your event.

Let me know if that helps at all or you need something different, cheers 😄

edkongz commented 6 years ago

Thanks @davidchase! I didn't think of it like that. Learn something new everyday. For anyone else I did the following:

    fromEvent("resize", window)
      .until(fromPromise(new Promise(resolve => this.unmount=resolve)))
      .forEach(console.log);

when I want to do cleanup I resolved the promise with the this.unmount() and everything worked.

davidchase commented 6 years ago

awesome glad to hear that worked and thanks for posting your example of how you are using it :)