1.0.0 • Published 3 years ago

trocar-class-events v1.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
3 years ago

README

Trocar class events

npm install trocar-class-events

Usage:

const {eventContainerify, createEvent} =require('trocar-class-events');
class Foo{
    #publish
    constructor(){
        this.#publish = eventContainerify(this);
        //You can internally subscribe
        const subscriptionId = this.subscribe("bar",this.onBar);
        this.detatch =()=>{
            console.log("detach was called");
            this.unsubscribe("bar",subscriptionId);
        }
    }
    onBar(event){
        console.log({name:"onBar Event from Foo",event});
    }
    bar(){
        this.#publish(createEvent("bar", {message:"a bar was called"}));
    }
}

var myFoo = new Foo();
console.log("no subscription yet");
myFoo.bar();
//You can externally subscribe
var id = myFoo.subscribe("bar",(event)=>{
    console.log("external subscription fired...");
});
console.log(`you need the id ${id} for unsubscribing`);
myFoo.bar();
myFoo.unsubscribe("bar",id);
console.log('unsubscribed happened');
myFoo.bar();
myFoo.detatch();
console.log("detaching onBar");
myFoo.bar();

Possible outputs:

no subscription yet
{
  name: 'onBar Event from Foo',
  event: {
    type: 'bar',
    correlation: '1195d1f9-b3f4-466b-8025-5a34df8e2971',
    eventDate: 1622403448779,
    message: 'a bar was called'
  }
}
you need the id fa8c3f59-a3bd-4027-a40f-ebaf3b8a58f5 for unsubscribing
{
  name: 'onBar Event from Foo',
  event: {
    type: 'bar',
    correlation: '102617da-0fc8-4ddd-9bdd-5d9bc8d7d7cb',
    eventDate: 1622403448781,
    message: 'a bar was called'
  }
}
external subscription fired...
unsubscribed happened
{
  name: 'onBar Event from Foo',
  event: {
    type: 'bar',
    correlation: '8649e21b-da5f-4e58-bf7e-d1c10b7a5b4b',
    eventDate: 1622403448782,
    message: 'a bar was called'
  }
}
detach was called
detaching onBar

Functions:

eventContainerify(objectToEventContainerify) returns publish event function.

Why not just attach a publish? then just anyone could call it, by returning it, we place the control back in your hands. In the Foo example we made it a private method.

objectToEventContainerify.subscribe(typeToSubscribe, callback) returns an id objectToEventContainerify.unsubscribe(typeTonUnsubscribeFrom, idToUnsubscribe)

publish(eventToPublish)

createEvent(eventType, dictionaryWithProperties)

takes the dictionaryWithProperties and adds:

  • type
  • correlation
  • eventDate

type is a string, the name of the event type. correlation is a string, serving for a correlationid if you are doing many things you might want to tie the events together. eventDate is the date the event was created.