Event Bus

Credit to u/galitork on reddit.com.

function Events() constructor {
	signals = [];
	
	subscribe = function(event, fn) {
		var i = array_length(signals);
		
		signals[i] = {
			name: event,
			func: fn
		}
	}
	
	unsubscribe = function(event) {
		var newSignals = [];
		var j = 0;
		
		for(var i = 0; i < array_length(signals); i++) {
			var signal = signals[i];
			
			if(signal.name != event) {
				newSignals[j] = signals[i];
				j++;
			}
		}
		
		signals = newSignals;
	}
	
	emit = function(event, data) {
		for(var i = 0; i < array_length(signals); i++) {
			var signal = signals[i];
			
			if(signal.name == event) {
				signal.func(data);
			}
		}
	}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s