public on()

in packages/geofire/src/GeoQuery.ts [183:215]


  public on(eventType: string, callback: Function): GeoCallbackRegistration {
    // Validate the inputs
    if (['ready', 'key_entered', 'key_exited', 'key_moved'].indexOf(eventType) === -1) {
      throw new Error('event type must be \'ready\', \'key_entered\', \'key_exited\', or \'key_moved\'');
    }
    if (typeof callback !== 'function') {
      throw new Error('callback must be a function');
    }

    // Add the callback to this query's callbacks list
    this._callbacks[eventType].push(callback);

    // If this is a 'key_entered' callback, fire it for every location already within this query
    if (eventType === 'key_entered') {
      const keys: string[] = Object.keys(this._locationsTracked);
      keys.forEach((key: string) => {
        const locationDict = this._locationsTracked[key];
        if (typeof locationDict !== 'undefined' && locationDict.isInQuery) {
          callback(key, locationDict.location, locationDict.distanceFromCenter);
        }
      });
    }

    // If this is a 'ready' callback, fire it if this query is already ready
    if (eventType === 'ready' && this._valueEventFired) {
      callback();
    }

    // Return an event registration which can be used to cancel the callback
    return new GeoCallbackRegistration(() => {
      this._callbacks[eventType].splice(this._callbacks[eventType].indexOf(callback), 1);
    });
  }