Identifiers

Identify a listener function call based on its call stack 🕵️

A listener identifier is an array of strings representing the current call stack in reverse chronological order (newest first).

Listener functions receive a listener identifier (lid) as the first argument.

Identifiers are mainly used to target listener bindings, but have other potential uses.

Pass the identifier along

Here we show how listener functions pass the lid along to the next listener function.

Create a library with listeners that call each other and save it as lidExample.ts:

lidExample.ts
class LidExample {
  public a(lid: string[]) {
    console.log(lid)
    this.b(lid)
  }
  
  public b(lid: string[]) {
    console.log(lid)
  }
}

export default new LidExample()

The identifier array is immutable and remains the same value for the scope of the function.

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

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

listener.load([], { lidExample })
lidExample.a([])

Execute main.ts and view the output:

$ ts-node main.ts
["lidExample.a"]
["lidExample.b", "lidExample.a"]

Custom identifiers

Its not heresy to simply prepend your own id to the lid as you pass it along:

customIdExample.ts
class CustomIdExample {
  public a(lid: string[]) {
    this.b(["customId", ...lid])
  }
  
  public b(lid: string[]) {
    console.log(lid)
      // ["customIdExample.b", "customId"]
  }
}

export default new CustomIdExample()

Automatic unique identifiers

By changing lid to lid_, we signal for listener to prepend a unique identifier to the listener function call:

uniqueIdExample.ts
class UniqueIdExample {
  public a(lid_: string[]) {
    console.log(lid_[1]) // a, b, c...
  }
}

export default new UniqueIdExample()

Unique identifier is a misnomer; the identifier is more like an alphanumeric counter that produces ids in the same order with each new execution.

Last updated