From 7325742c14f27be5b3e72d5e9b513d805c736c5a Mon Sep 17 00:00:00 2001 From: Jonathan Beezley Date: Fri, 14 Mar 2014 07:53:12 -0400 Subject: [PATCH] adding generic event handling inside the object class --- src/core/object.js | 77 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 76 insertions(+), 1 deletion(-) diff --git a/src/core/object.js b/src/core/object.js index 19ac13de1b..d756aee43f 100644 --- a/src/core/object.js +++ b/src/core/object.js @@ -4,7 +4,7 @@ */ /*jslint devel: true, forin: true, newcap: true, plusplus: true*/ -/*jslint white: true, indent: 2*/ +/*jslint white: true, indent: 2, unparam: true*/ /*global geo, ogs, inherit, $, HTMLCanvasElement, Image*/ /*global vgl, document*/ @@ -23,6 +23,81 @@ geo.object = function(cfg) { if (!(this instanceof geo.object)) { return new geo.object(); } + + var m_eventHandlers = {}; + +////////////////////////////////////////////////////////////////////////////// +/** + * Bind an event handler to this object + */ +////////////////////////////////////////////////////////////////////////////// + this.on = function (event, handler) { + if (Array.isArray(event)) { + event.forEach(function (e) { + this.on(e, handler); + }); + return this; + } + if (!m_eventHandlers.hasOwnProperty(event)) { + m_eventHandlers[event] = []; + } + m_eventHandlers[event].push(handler); + return this; + }; + +////////////////////////////////////////////////////////////////////////////// +/** + * Trigger an event (or events) on this object and call all handlers + */ +////////////////////////////////////////////////////////////////////////////// + this.trigger = function (event, args) { + if (Array.isArray(event)) { + event.forEach(function (e) { + this.trigger(e, args); + }); + return this; + } + if (m_eventHandlers.hasOwnProperty(event)) { + m_eventHandlers[event].forEach(function (handler) { + handler(args); + }); + } + return this; + }; + +////////////////////////////////////////////////////////////////////////////// +/** + * Remove handlers from an event (or an array of events). + * + * @param arg a function or array of functions to remove from the events + * or if falsey remove all handlers from the events + */ +////////////////////////////////////////////////////////////////////////////// + this.off = function (event, arg) { + if (Array.isArray(event)) { + event.forEach(function (e) { + this.off(e, arg); + }); + return this; + } + if (!arg) { + m_eventHandlers[event] = []; + } else if (Array.isArray(arg)) { + arg.forEach(function (handler) { + this.off(event, handler); + }); + return this; + } + // What do we do if the handler is not already bound? + // ignoring for now... + if (m_eventHandlers.hasOwnProperty(event)) { + m_eventHandlers[event] = m_eventHandlers[event].filter(function (f) { + return f !== arg; + }); + } + return this; + }; + vgl.object.call(this); return this;