map.apps Bundle APIs 4.20.0
    Preparing search index...

    Function createObservers

    • Observers encapsulates a collection of connections to event emitters, like Evented, Mutable, Watches and the like. It therefor helps you to manage multiple event connections by grouping them - e.g. for cleaning all connections at once.

      Parameters

      • Optionaloptions: ObserverOptions

        optional parameters to customize the creation

      Returns Observers

      import Observers from "apprt-core/Observers";
      import { Evented } from "apprt-core/Events";

      const eventSource = new Evented();
      const observers = Observers();
      // track connection to eventSource
      observers.add(eventSource.on("event", ()=>{ ... }));
      // if the connection needs to be cleaned call
      observers.clean();
      const eventSourceA = new Evented();
      const eventSourceB = new Evented();
      const observers = Observers();
      // track connection to eventSourceA, but in group "a"
      observers.group("a").add(eventSourceA.on("event", ()=>{ ... }));
      // track connection to eventSourceB, but in group "b"
      observers.group("b").add(eventSourceB.on("event", ()=>{ ... }));
      // if "a" is not longer required
      observers.group("a").clean();
      // if "b" is not longer required (shows alternative)
      observers.clean("b");
      // if none of the connections are required anymore clean all
      observers.clean();
      // The bind/rebind functionality helps to encapsulate the code to connect to an observable.
      // When the observable target changes a simple call to 'bind'
      // rexecutes the connection code and clears the old connection.

      import createObservers, { Observers } from "apprt-core/Observers";
      import { Evented } from "apprt-core/Events";

      interface CustomEvents {
      "changed": boolean
      }

      class Controller {
      private observers: Observers | undefined;
      private events: any[] = [];
      constructor() {
      this.events = [];
      this.observers = createObservers({
      // rebind is executed if Observers.bind is called, and used to reconnect to a new source instance
      rebind: (observers, source) => {
      const eventSource = source as Evented<CustomEvents>;
      observers.add(eventSource.on("change", (evt) => {
      this.events.push(evt);
      }));
      }
      });
      }
      connect(eventSource: Evented<CustomEvents>) {
      // observe new event source
      this.observers!.bind(eventSource);
      }
      disconnect() {
      // disconnect from event source
      this.observers!.clean();
      }
      }