如何创建基于名称的对象数组?

时间:2017-11-04 22:38:38

标签: typescript typescript-typings

目前,我尝试查看TypeScript

在我的旧JavaScript - 源上我有一个简单的基于名称的Array-Object用于EventListener:

let _events		= {};

this.addEventListener = function addEventListener(name, callback) {
		if(typeof(_events[name]) == 'undefined') {
			_events[name] = [];
		}
		
		_events[name].push(callback);
	};
	
	this.fireEvent = function fireEvent() {
		let fired	= false;
		let args	= new Array();
		let name	= arguments[0];
		
		if(typeof(_events[name]) == 'undefined') {
			return;
		}
		
		for(var index = 1; index < arguments.length; index++) {
			args.push(arguments[index]);
		}
	
		_events[name].forEach(function onEvent(event) {
			fired = true;
			event.apply(this, args);
		}.bind(this));
		
		return fired;
	};

我如何在TypeScript中创建相同的方法?

以下是样本结果:

{
    "init": [callback, callback, callback],
    "otherEvent": [callback, callback]
}

1 个答案:

答案 0 :(得分:0)

您可以使用TypeScript和一些最新的ES6功能实现相同的功能。例如,不使用对象_events作为键/值映射,而是可以使用ES6映射:

class EventManager {

    private _events: Map<string, Array<Function>>;

    public addEventListener(name: string, callback: Function) {
        if(this._events.has(name) === false) {
            this._events.set(name, [callback]);
        } else {
            const previosCallbacks = this._events.get(name);
            previosCallbacks.push(callback);
            this._events.set(name, previosCallbacks);
        }
    }

    public fireEvent(name: string, ...args: any[]) {

        let fired = false;

        if (this._events.has(name) === false) {
            return;
        }

        this._events.get(name).forEach((cb) => {
            fired = true;
            cb(...args);
        });

        return fired;
    }

}