2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 * Created by obarda on 7/4/2016.
24 import * as _ from "lodash";
25 import {Dictionary} from "../utils/dictionary/dictionary";
27 interface IEventListenerService {
31 interface ICallbackData {
36 export class EventListenerService implements IEventListenerService {
38 public observerCallbacks:Dictionary<string, ICallbackData[]> = new Dictionary<string, Array<ICallbackData>>();
40 //register an observer + callback
41 public registerObserverCallback = (eventName:string, callback:Function, ...args) => {
47 if (this.observerCallbacks.containsKey(eventName)) {
48 let callbacks = this.observerCallbacks.getValue(eventName);
50 // Only insert the callback if the callback is different from existing callbacks.
51 for (let i = 0; i < callbacks.length; i++) {
52 if (callbacks[i].callback.toString() === callback.toString()) {
53 return; // Do not add this callback.
57 callbacks.push(callbackData);
58 this.observerCallbacks.setValue(eventName, callbacks);
60 this.observerCallbacks.setValue(eventName, [callbackData]);
64 //unregister an observer
65 public unRegisterObserver = (eventName:string, callbackFunc?:Function) => {
66 if (this.observerCallbacks.containsKey(eventName)) {
68 let callbacks: ICallbackData[] = this.observerCallbacks.getValue(eventName);
69 if(callbacks.length === 1) {
70 this.observerCallbacks.remove(eventName);
72 let filterCallbacks = _.filter(callbacks, (callBackObj) => {
73 return callBackObj.callback != callbackFunc;
75 this.observerCallbacks.setValue(eventName, filterCallbacks);
81 public notifyObservers = function (eventName:string, ...args) {
82 _.forEach(this.observerCallbacks.getValue(eventName), (callbackData:ICallbackData) => {
83 callbackData.callback(...args);