Join

Connect libraries without introducing "hard" production dependencies.

Create a library that joins itself with another and save it as joinExample.ts:

joinExample.ts
import join from "@listener-js/join"
import logger from "./logger"

class JoinExample {
  private join: typeof join.join
  private log: typeof logger.log
  
  public hi() {
    this.log("hi!")
  }
  
  private listenerLoaded(lid: string[]) {
    this.join(lid, "logger.log")
  }
}

export default new JoinExample()

The logger library in this example comes from the getting started section.

The imports in this example has no effect on compiled output. They are purely for accessing types.

Load the listener libraries, call the hi function, and save it as main.ts:

main.ts
import listener from "@listener-js/listener"
import join from "@listener-js/join"

import joinExample from "./joinExample"
import logger from "./logger"

listener.load([], { join, joinExample, logger })
joinExample.hi()

Execute main.ts and view the output:

$ ts-node main.ts
hi!

Asynchronous loading

In the previous example, we also could have loaded the libraries using dynamic imports:

main.ts
import listener from "@listener-js/listener"
import join from "@listener-js/join"

import joinExample as je from "./joinExample"

listener
  .load([], {
    join,
    joinExample: import("./joinExample"),
    logger: import("./logger"),
  })
  .then(
    ({ joinExample }: { joinExample: typeof je }): void => {
      joinExample.hi()
    }
  )

The top-level joinExample import in this example has no effect on compiled output. It is purely for accessing types.

Listener joined callback

The listenerJoined callback is executed on the library that is joined to another library.

Define a listenerJoined callback function within a listener library:

joinedExample.ts
import { ListenerJoinEvent } from "@listener-js/join"

export class JoinedExample {
  private listenerJoined(
    lid: string[],
    event: ListenerJoinEvent
  ) {
    // called when this library joins another
  }
}

export default new JoinedExample()

Callback arguments

The listenerJoined callback receive two arguments, a listener id (lid) and a listener join event object that adds extra information to the listener event:

export interface ListenerJoinEvent extends ListenerEvent {
  joinInstance: any
}

Last updated