Event Management
 fix the event object
516931
function(src) {
  if (src.__src) return src;
  if (typeof src === 'string') src = { type: src };

  var event = { __src: src }
    , target;

  target = src.target || src.srcElement || document;
  event.target = target.nodeType !== 3 
               ? target 
               : target.parentNode;
  event.currentTarget = src.currentTarget || target;
  event.type = src.type;

  event.key = function() {
    // mozilla may use .which
    return src.which || src.keyCode
      || src.charCode || src.key
      || src.char || 0;
  };

  event.button = function() {
    // webkit uses .which
    var button = src.button != null
      ? +src.button
      : src.which != null
        ? src.which - 1
        : undefined;

    if (DOM.env.ie) {
      // IE needs fixing: 1 -> 0, 4 -> 1, 2 -> 2
      button = button === 1 
        ? 0 
        : button === 4 ? 1 : button;
    }

    return {
      left: button === 0,
      middle: button === 1,
      right: button === 2
    };
  };

  event.cursor = function(x, y) {
    if (typeof src.clientX === 'number') {
      var doc = DOM.getDocument(target)
        , root = doc.documentElement
        , body = doc.body;

      x = src.clientX
        + (doc.scrollLeft || root.scrollLeft || body.scrollLeft || 0)
        - (doc.clientLeft || root.clientLeft || body.clientLeft || 0);
      y = src.clientY
        + (doc.scrollTop || root.scrollTop || body.scrollTop || 0)
        - (doc.clientTop || root.clientTop || body.clientTop || 0);
    } else if (typeof src.pageX === 'number') {
      x = src.pageX;
      y = src.pageY;
    }
    return { x: x, y: y };
  };

  if (src.type === 'mouseover' 
      || src.type === 'mouseout') {
    if (!src.relatedTarget) {
      event.relatedTarget = src.type === 'mouseover'
                          ? src.fromTarget 
                          : src.toTarget;
    } else {
      event.relatedTarget = src.relatedTarget;
    }
  }

  //event.returnValue = src.returnValue;
  event.preventDefault = function() {
    if (src.preventDefault) {
      src.preventDefault();
    }
    src.returnValue = false;
  };
  event.stopPropagation = function() {
    if (src.stopPropagation) {
      src.stopPropagation();
    }
    src.cancelBubble = true;
  };
  event.stop = function() {
    event.stopPropagation();
    event.preventDefault();
  };
  event.kill = function() {
    event.stop();
    event.dead = true;
  };

  return event;
}
722815
def complete_event(self, event_id: str):
        """"""
        event_ids = DB.get_list(self._processed_key)
        if event_id not in event_ids:
            raise KeyError('Unable to complete event. Event {} has not been '
                           'processed (ie. it is not in the processed '
                           'list).'.format(event_id))
        DB.remove_from_list(self._processed_key, event_id, pipeline=True)
        key = _keys.completed_events(self._object_type, self._subscriber)
        DB.append_to_list(key, event_id, pipeline=True)
        DB.execute()
403160
public void subscribeEvent(Object object) {
        if (object instanceof Class) {
            object = locator.createAndInitialize((Class) object);
        } else {
            locator.inject(object);
            locator.postConstruct(object);
        }
        getEventBus().subscribe(object);
    }
164501
def create_event_object(self,
                            event_type,
                            code,
                            value,
                            timeval=None):
        """"""
        if not timeval:
            self.update_timeval()
            timeval = self.timeval
        try:
            event_code = self.type_codes[event_type]
        except KeyError:
            raise UnknownEventType(
                "We don't know what kind of event a %s is." % event_type)

        event = struct.pack(EVENT_FORMAT,
                            timeval[0],
                            timeval[1],
                            event_code,
                            code,
                            value)
        return event
1343022
function(view, event_name, event_object, targets) {

		this._dispatchCallback(
			view,
			targets,
			this._callHandleEvent,
			{
				event_name: event_name,
				event_object: event_object
			},
			this._global_event_targets
		);

	}
644574
def _update_event(self, event_index, event_state, event_type, event_value,
                      proc_list, proc_desc, peak_time):
        """"""
        if event_state == "OK" or event_state == "CAREFUL":
            # Reset the automatic process sort key
            self.reset_process_sort()

            # Set the end of the events
            endtime = time.mktime(datetime.now().timetuple())
            if endtime - self.events_list[event_index][0] > peak_time:
                # If event is > peak_time seconds
                self.events_list[event_index][1] = endtime
            else:
                # If event <= peak_time seconds, ignore
                self.events_list.remove(self.events_list[event_index])
        else:
            # Update the item
            self.set_process_sort(event_type)

            # State
            if event_state == "CRITICAL":
                self.events_list[event_index][2] = event_state
            # Min value
            self.events_list[event_index][6] = min(self.events_list[event_index][6],
                                                   event_value)
            # Max value
            self.events_list[event_index][4] = max(self.events_list[event_index][4],
                                                   event_value)
            # Average value
            self.events_list[event_index][7] += event_value
            self.events_list[event_index][8] += 1
            self.events_list[event_index][5] = (self.events_list[event_index][7] /
                                                self.events_list[event_index][8])

            # TOP PROCESS LIST (only for CRITICAL ALERT)
            if event_state == "CRITICAL":
                events_sort_key = self.get_event_sort_key(event_type)
                # Sort the current process list to retreive the TOP 3 processes
                self.events_list[event_index][9] = sort_stats(proc_list,
                                                              events_sort_key)[0:3]
                self.events_list[event_index][11] = events_sort_key

            # MONITORED PROCESSES DESC
            self.events_list[event_index][10] = proc_desc

        return True
1075920
protected void handleUpdatedObject(final Object object) {
		runWithWriteLock(new Runnable() {
			public void run() {
				int index = getFinalEventList().indexOf(object);
				if (index >= 0) {
					getFinalEventList().set(index, object);
				}
			}
		});
	}
1364003
function( event ) {
	event.type = event.data;
	jQuery.event.handle.apply( this, arguments );
}
836966
function _gpfEventsTriggerHandler (event, eventsHandler, resolvePromise) {
    var eventHandler = _getEventHandler(event, eventsHandler);
    eventHandler(event);
    if (undefined !== resolvePromise) {
        resolvePromise(event);
    }
}
670578
def set_event_handler(self, event, handler):
        """"""
        # QUESTION: Should we raise an exception if `event` is not in some
        # known event-type list?

        self._prepare_persistence_engine()

        callbacks = self._options.get('callbacks', {})
        callbacks[event] = handler
        self._options['callbacks'] = callbacks
374257
function (event) {
            var own = this;
            var returnValue = true;
            // grab the event object (IE uses a global event object)
            event = event || own._fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
            // get a reference to the hash table of event handlers
            var handlers = this.events[event.type];
            // execute each event handler
            for (var i in handlers) {
                var _handleEvent = handlers[i];
                if (_handleEvent(event) === false) {
                    returnValue = false;
                }
            }
            return returnValue;
        }
1137979
function event(publicAPI, model, eventName, asynchrounous = true) {
  const callbacks = [];
  const previousDestroy = publicAPI.destroy;

  function off(index) {
    callbacks[index] = null;
  }

  function on(index) {
    function unsubscribe() {
      off(index);
    }
    return Object.freeze({ unsubscribe });
  }

  publicAPI[`fire${capitalize(eventName)}`] = (...args) => {
    if (model.deleted) {
      console.log('instance deleted - can not call any method');
      return;
    }

    function processCallbacks() {
      callbacks.forEach((callback) => {
        if (callback) {
          try {
            callback.apply(publicAPI, args);
          } catch (errObj) {
            console.log('Error event:', eventName, errObj);
          }
        }
      });
    }

    if (asynchrounous) {
      setImmediate(processCallbacks);
    } else {
      processCallbacks();
    }
  };

  publicAPI[`on${capitalize(eventName)}`] = (callback) => {
    if (model.deleted) {
      console.log('instance deleted - can not call any method');
      return null;
    }

    const index = callbacks.length;
    callbacks.push(callback);
    return on(index);
  };

  publicAPI.destroy = () => {
    previousDestroy();
    callbacks.forEach((el, index) => off(index));
  };
}
912042
def OnUndo(self, event):
        """"""

        statustext = undo.stack().undotext()
        undo.stack().undo()

        # Update content changed state
        try:
            post_command_event(self.grid.main_window,
                               self.grid.ContentChangedMsg)
        except TypeError:
            # The main window does not exist any more
            pass

        self.grid.code_array.result_cache.clear()

        post_command_event(self.grid.main_window, self.grid.TableChangedMsg,
                           updated_cell=True)

        # Reset row heights and column widths by zooming
        self.grid.actions.zoom()

        # Change grid table dimensions
        self.grid.GetTable().ResetView()

        # Update TableChoiceIntCtrl
        shape = self.grid.code_array.shape
        post_command_event(self.main_window, self.grid.ResizeGridMsg,
                           shape=shape)

        # Update toolbars
        self.grid.update_entry_line()
        self.grid.update_attribute_toolbar()

        post_command_event(self.grid.main_window, self.grid.StatusBarMsg,
                           text=statustext)
622486
function (object, event, callback) {
        var index = this.indexOf(object);
        var listener = this.listeners[index];
        if (listener) {
            var callbacks = listener.events[event];
            if (callbacks) {
                var index = callbacks.indexOf(callback);
                if (index != -1) {
                    callbacks.splice(index, 1);
                }

                // remove the array when empty
                if (callbacks.length == 0) {
                    delete listener.events[event];
                }
            }

            // count the number of registered events. remove listener when empty
            var count = 0;
            var events = listener.events;
            for (var e in events) {
                if (events.hasOwnProperty(e)) {
                    count++;
                }
            }
            if (count == 0) {
                delete this.listeners[index];
            }
        }
    }
609887
function _cleanUpEvents(elem, type) {
  var data = Dom.getElData(elem);

  // Remove the events of a particular type if there are none left
  if (data.handlers[type].length === 0) {
    delete data.handlers[type];
    // data.handlers[type] = null;
    // Setting to null was causing an error with data.handlers

    // Remove the meta-handler from the element
    if (elem.removeEventListener) {
      elem.removeEventListener(type, data.dispatcher, false);
    } else if (elem.detachEvent) {
      elem.detachEvent('on' + type, data.dispatcher);
    }
  }

  // Remove the events object if there are no types left
  if (Object.getOwnPropertyNames(data.handlers).length <= 0) {
    delete data.handlers;
    delete data.dispatcher;
    delete data.disabled;
  }

  // Finally remove the element data if there is no data left
  if (Object.getOwnPropertyNames(data).length === 0) {
    Dom.removeElData(elem);
  }
}
657543
function globalEventHandler(event) {
    if (listeners[event.type]) {
      listeners[event.type].forEach(function(currentHandler) {
        currentHandler.call(this, event);
      }, this);
    }
  }
1362852
def on(self, event, handler=None):
        """"""
        if isinstance(event, str) and ' ' in event:  # event is list str-based
            self.on(event.split(' '), handler)
        elif isinstance(event, list):  # many events contains same handler
            for each in event:
                self.on(each, handler)
        elif isinstance(event, dict):  # event is a dict of <event, handler>
            for key, value in event.items():
                self.on(key, value)
        elif isinstance(handler, list):  # handler is a list of handlers
            for each in handler:
                self.on(event, each)
        elif isinstance(handler, Event):  # handler is Event object
            self.events[event] = handler  # add or update an event
            setattr(self, event, self.events[event])  # self.event.trigger()
        elif event in self.events:  # add a handler to an existing event
            self.events[event].on(handler)
        else:  # create new event with a handler attached
            self.on(event, Event(handler))