Use a Publish-Subscribe (EventEmitter) pattern to decouple the image logic (Taggd class) from the marker logic (Tag class). This allows the system to notify other components when tags are added or moved.
To allow subscribers to intercept or cancel actions, implement a check where the event emitter returns a boolean value. If the subscriber returns false, the original operation is canceled.
import EventEmitter from "../utils/event-emitter";
class Taggd extends EventEmitter {
addTag(tag: Tag) {
// Emit event and check if it was canceled by a listener
const isCanceled = !this.emit("taggd.tag.add", this, tag);
if (!isCanceled) {
// Proceed with adding the tag
}
return this;
}
}
// Usage
let taggd = new Taggd(image);
taggd.on("taggd.tag.add", function () {
console.log('Tag added');
});