CFLib.org – Common Function Library Project

createEventObject()

Last updated December 5, 2013

author

Adam Cameron

Version: 1 | Requires: CF10 | Library: CFMLLib

Description:
Returns a lightweight object (just a struct) containing on() / off() / trigger() functions to facilitate event-driven coding in CFML

Return Values:
A struct containing functions on(), off() and trigger()

Example:

event = createEventObject();

event.on("TestEvent", function(){writeOutput("Hello World<br>");});
event.trigger("TestEvent");

Parameters:

No arguments.

Full UDF Source:

/**
 * Creates functions for event-handling in CFML
 * v1.0 by Adam Cameron
 * 
 * @return A struct containing functions on(), off() and trigger() 
 * @author Adam Cameron (dac.cfml@gmail.com) 
 * @version 1.0, December 5, 2013 
 */
function createEventObject(){
	var eventContainer = {};
	return {
		on = function(required string event, required function handler, struct data={}){
			if (!structKeyExists(eventContainer, event)){
				eventContainer[event] = [];
			}
			arrayAppend(eventContainer[event], arguments);
		},
		trigger = function(required string event, struct additionalParameters={}){
			if (structKeyExists(eventContainer, event)){
				for (eventEntry in eventContainer[event]){
					var eventObj = {
						event = event,
						data = eventEntry.data
					};
					eventEntry.handler(event=eventObj, argumentCollection=additionalParameters);
				}
			}
		},
		off = function(required string event){
			structDelete(eventContainer, event);
		}
	};
}
blog comments powered by Disqus

Search CFLib.org


Latest Additions

Kevin Cotton added
date2ExcelDate
May 5, 2016

Raymond Camden added
CapFirst
April 25, 2016

Chris Wigginton added
loremIpsum
January 18, 2016

Gary Stanton added
calculateArrival...
November 19, 2015

Sebastiaan Naafs - van Dijk added
getDaysInQuarter
November 13, 2015

Created by Raymond Camden / Design by Justin Johnson