Source: src/main/javascript/oracle/oj/ojcore/EventSource.js

Oracle® JavaScript Extension Toolkit (JET)
3.2.0

E87541-01

/**
 * Copyright (c) 2014, Oracle and/or its affiliates.
 * All rights reserved.
 */

/**
 * @preserve Copyright 2013 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

/*jslint browser: true*/

/**
 * @export
 * @class oj.EventSource
 * @classdesc Object which supports subscribing to and firing events
 * @constructor
 */
oj.EventSource = function()
{
    this.Init();
};

// Subclass from oj.Object 
oj.Object.createSubclass(oj.EventSource, oj.Object, "oj.EventSource");

/**
 * Initializes the instance.
 * @export
 */
oj.EventSource.prototype.Init = function()
{
    this._eventHandlers = [];
    oj.EventSource.superclass.Init.call(this);
};

/**
 * Attach an event handler
 * @param {string} eventType eventType
 * @param {function(Object)} eventHandler event handler function
 * @export
 */
oj.EventSource.prototype.on = function(eventType, eventHandler)
{
    var foundEventHandler = false, i;
    for (i = 0; i < this._eventHandlers.length; i++)
    {
        if (this._eventHandlers[i]['eventType'] == eventType && 
            this._eventHandlers[i]['eventHandlerFunc'] == eventHandler)
        {
            foundEventHandler = true;
            break;
        }
    }
    if (!foundEventHandler) {
        this._eventHandlers.push({'eventType': eventType, 'eventHandlerFunc': eventHandler});
    }
};

/**
 * Detach an event handler
 * @param {string} eventType eventType
 * @param {function(Object)} eventHandler event handler function
 * @export
 */
oj.EventSource.prototype.off = function(eventType, eventHandler)
{
    var i;
    for (i = this._eventHandlers.length-1; i >= 0; i--)
    {
        if (this._eventHandlers[i]['eventType'] == eventType && 
            this._eventHandlers[i]['eventHandlerFunc'] == eventHandler)
        {
            this._eventHandlers.splice(i, 1);
            break;
        }
    }
};

/**
 * Handle the event
 * @param {string} eventType  event type
 * @param {Object} event  event
 * @return {boolean} Returns false if event is cancelled
 * @export
 */
oj.EventSource.prototype.handleEvent = function(eventType, event)
{
    var i, returnValue;
    for (i = 0; i < this._eventHandlers.length; i++)
    {
        var eventHandler = this._eventHandlers[i];
        if (eventHandler['eventType'] == eventType)
        {
            returnValue = eventHandler['eventHandlerFunc'].apply(this, Array.prototype.slice.call(arguments).slice(1));
            
            if (returnValue === false)
            {
                // event cancelled
                return false;
            }
        }
    }
    
    return true;
};