Observable From Event With Take Until
Create an observable from DOM events with takeUntil teardown for reactive stream composition and automatic unsubscription.
Code
export function fromEvent(target,name){return{subscribe(obs){const h=(...a)=>{try{obs.next?.(...a);}catch(e){obs.error?.(e);}};target.addEventListener(name,h);return{unsubscribe:()=>target.removeEventListener(name,h)};},takeUntil(notifier){return{subscribe(obs){const sub=this.subscribe(obs);const un=notifier.subscribe({next:()=>sub.unsubscribe()});return{unsubscribe:()=>{sub.unsubscribe();un.unsubscribe();}};}};}};}How the snippet works
The working surface is the functions h and fromEvent — everything else is wiring.
The result comes back as an object carrying name.
Using it
The primary signature is export function fromEvent(target,name)
fromEvent is what another module would consume; nothing else here is load-bearing for callers.
The call returns name.
Interactive Tools for This Topic
FAQ
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it. The file defines `h`, `fromEvent` at load time.
- What does `fromEvent` return?
- An object carrying `name`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.