Decorator for subscribing a function to a specific event.

        :param event: Name of the event to subscribe to.
        :type event: str

        :return: The outer function.
        :rtype: Callable
504584
def on(self, event: str) -> Callable:
        

        def outer(func):
            self.add_event(func, event)

            @wraps(func)
            def wrapper(*args, **kwargs):
                return func(*args, **kwargs)

            return wrapper

        return outer
1043035
def trigger(self, event, *args, **kw):
        
        observers = self._pool.get(event)

        # If no observers registered for the event, do no-op
        if not observers or len(observers) == 0:
            return None

        # Trigger observers coroutines in FIFO sequentially
        for fn in observers:
            # Review: perhaps this should not wait
            yield from fn(*args, **kw)
502953
function Subscriber(opts) {
  opts = opts || {};

  this._channel = opts.channel || 'default';
  this._subscribers = [];

  /* for mocking */
  var addEventListener = opts.addEventListener || window.addEventListener;
  var attachEvent = opts.attachEvent || window.attachEvent;

  var _this = this;
  function onMessage(e) {
    var event = parse(e.data);
    if (event.channel === _this._channel) {
      for (var i = 0, len = _this._subscribers.length; i < len; i++) {
        _this._subscribers[i].apply({}, event.args);
      }
    }
  }

  if (addEventListener) {
    addEventListener('message', onMessage, false);
  } else {
    attachEvent('onmessage', onMessage, false);
  }
}
800117
def emit_only(self, event: str, func_names: Union[str, List[str]], *args,
                  **kwargs) -> None:
        
        if isinstance(func_names, str):
            func_names = [func_names]

        for func in self._event_funcs(event):
            if func.__name__ in func_names:
                func(*args, **kwargs)
926947
def subscribe_to_hub(self, event, callback, secret=github.GithubObject.NotSet):
        
        return self._hub("subscribe", event, callback, secret)
364318
def subscribe(self, callback, existing=True):
        
        if callback in self.callbacks:
            return
        self.callbacks.append(callback)
        if not existing:
            return
        for dist in self:
            callback(dist)
9363
def emit(self, event, *args, **kwargs):
        
        for func in self._registered_events[event].values():
            func(*args, **kwargs)
579415
def handle_event(self, event):
        
        subscription_id = event.subscription_id
        if subscription_id in self._subscriptions:
            # FIXME: [1] should be a constant
            handler = self._subscriptions[subscription_id][SUBSCRIPTION_CALLBACK]
            WampSubscriptionWrapper(self,handler,event).start()
1147287
def subscribe(self, event):
        """"""
        uuids = event.data

        if not isinstance(uuids, list):
            uuids = [uuids]

        subscribed = []
        for uuid in uuids:
            try:
                self._add_subscription(uuid, event)
                subscribed.append(uuid)
            except KeyError:
                continue

        result = {
            'component': 'hfos.events.objectmanager',
            'action': 'subscribe',
            'data': {
                'uuid': subscribed, 'success': True
            }
        }
        self._respond(None, result, event)
1253489
def _subscribed_event_count(self) -> int:
        
        event_counter = Counter()  # type: Dict[Any, int]

        for key, values in self._events.items():
            event_counter[key] = len(values)

        return sum(event_counter.values())
44673
def subscribe(self,
                  event_type: Type[TSubscribeEvent],
                  handler: Callable[[TSubscribeEvent], None]) -> Subscription:
        
        if event_type not in self._handler:
            self._handler[event_type] = []

        casted_handler = cast(Callable[[BaseEvent], Any], handler)

        self._handler[event_type].append(casted_handler)

        return Subscription(lambda: self._handler[event_type].remove(casted_handler))
156961
def event_emitter(cls_=None, *, events=('*', )):
    

    # create a dictionary from items in the 'events' parameter and with empty
    # lists as values
    event_dict = dict.fromkeys(events, [])

    # if '*' was in the events tuple - then pop it out of the event_dict
    # and store the fact that we may allow any event name to be added to the
    # event emitter.
    allow_any_eventname = event_dict.pop('*', False) == []

    def _event_emitter(cls):

        def on(self, name, callback):
            """
            Add a callback to the event named 'name'. Returns the object for
            chained 'on' calls.
            """
            if not (callable(callback) or isawaitable(callback)):
                raise ValueError("Callback not callable: %r" % callback)

            try:
                event_dict[name].append(callback)
            except KeyError:
                if allow_any_eventname:
                    event_dict[name] = [callback]
                else:
                    msg = "Event Emitter has no event {!r}".format(name)
                    raise KeyError(msg)

            return self

        async def emit(self, name):
            """
            Coroutine which executes each of the callbacks added to the event
            identified by 'name'
            """
            for cb in event_dict[name]:
                if isawaitable(cb):
                    await cb
                else:
                    cb()

        cls.on = on
        cls.emit = emit

        return cls

    if cls_ is None:
        return _event_emitter
    else:
        return _event_emitter(cls_)
951937
function (event) {
    this.debug("Requesting subscription for " + event);
    sendReceive.call(this, {'do': 'subscribe', params: [event]}, function (result) {
        if (result.success) {
            this.debug("Succesfully subscribed to %s", event);
        } else {
            this.debug("Subscription request for %s failed", event);
        }
    });
    this.subscribedEvents.push(event);
}
651520
def _trigger_event(self, event):
    

    if event is None or event not in self.__listeners:
      raise ValueError('invalid event type: {0!r}'.format(event))

    # Check the event has not already been triggered, then mark
    # the event as triggered.
    if event in self.__event_set:
      raise RuntimeError('event already triggered: {0!r}'.format(event))
    self.__event_set.add(event)
    listeners = self.__listeners[event] + self.__listeners[None]

    # Remove one-off listeners.
    self.__listeners[event][:] = (l for l in self.__listeners[event] if not l.once)
    self.__listeners[None][:] = (l for l in self.__listeners[None] if not l.once)

    for listener in listeners:
      # XXX: What to do on exceptions? Catch and make sure all listeners
      # run through? What to do with the exception(s) then?
      listener.callback(self, event)
225031
def handle(event):
        
        def dec(func):
            if not hasattr(func, '_handle_events'):
                func._handle_events = set()
            func._handle_events.add(event)
            return func

        return dec
1363178
def handler(event):
    """"""
    def decorator(fn):
        def apply(cls):
            event.connect(fn, sender=cls)
            return cls

        fn.apply = apply
        return fn
    return decorator
255380
public int subscribe_event(DeviceProxy device,
                               int event,
                               CallBack callback,
                               int max_size,
                               boolean stateless)
            throws DevFailed {
        //	Set the event name;
        String event_name = eventNames[event];
        ApiUtil.printTrace("=============> subscribing for " + device.name() + "." + event_name);

        //	if no callback (null), create EventQueue
        if (callback == null && max_size >= 0) {
            //	Check if already created (in case of reconnection stateless mode)
            if (device.getEventQueue() == null)
                if (max_size > 0)
                    device.setEventQueue(new EventQueue(max_size));
                else
                    device.setEventQueue(new EventQueue());
        }

        String deviceName = device.fullName();
        String callback_key = deviceName.toLowerCase();

        //  Not added for Interface change event (Special case)
        /*
        if (device.get_idl_version()>=5)
            callback_key += ".idl" + device.get_idl_version()+ "_" + event_name;
        else
        */
            callback_key += "." + event_name;
        try {
            //	Inform server that we want to subscribe and try to connect
            ApiUtil.printTrace("calling callEventSubscriptionAndConnect() method");
            callEventSubscriptionAndConnect(device, event_name);
            ApiUtil.printTrace("call callEventSubscriptionAndConnect() method done");
        } catch (DevFailed e) {
            //  re throw if not stateless
            if (!stateless || e.errors[0].desc.equals(ZMQutils.SUBSCRIBE_COMMAND_NOT_FOUND)) {
                throw e;
            }
            else {
                //	Build Event CallBack Structure and add it to map
                subscribe_event_id++;
                EventCallBackStruct new_event_callback_struct =
                        new EventCallBackStruct(device,
                                event_name,
                                "",
                                callback,
                                max_size,
                                subscribe_event_id,
                                event,
                                false);
                failed_event_callback_map.put(callback_key, new_event_callback_struct);
                return subscribe_event_id;
            }
        }

        //	Prepare filters for heartbeat events on channelName
        String channelName = device_channel_map.get(deviceName);
        if (channelName==null) {
            //  If from notifd, tango host not used.
            int start = deviceName.indexOf('/', "tango:// ".length());
            deviceName = deviceName.substring(start+1);
            channelName = device_channel_map.get(deviceName);
        }
        EventChannelStruct event_channel_struct = channel_map.get(channelName);
        event_channel_struct.last_subscribed = System.currentTimeMillis();

        //	Check if a new event or a re-trying one
        int eventId;
        EventCallBackStruct failed_struct = failed_event_callback_map.get(callback_key);
        if (failed_struct == null) {
            //	It is a new one
            subscribe_event_id++;
            eventId = subscribe_event_id;
        } else
            eventId = failed_struct.id;

        //	Build Event CallBack Structure if any
        EventCallBackStruct new_event_callback_struct =
                new EventCallBackStruct(device,
                        event_name,
                        channelName,
                        callback,
                        max_size,
                        eventId,
                        event,
                        true);
        new_event_callback_struct.consumer  = this;
        event_callback_map.put(callback_key, new_event_callback_struct);


        //	Thread to read the attribute by a simple synchronous call and
        //	force callback execution after release monitor.
        //	This is necessary for the first point in "change" mode,
        //	but it is not necessary to be serialized in case of
        //	read attribute or callback execution a little bit long.
        if ((event == CHANGE_EVENT) ||
                (event == PERIODIC_EVENT) ||
                (event == PIPE_EVENT) ||
                (event == ARCHIVE_EVENT) ||
                (event == USER_EVENT) ||
                (event == INTERFACE_CHANGE) ||
                (event == ATT_CONF_EVENT)) {
            new PushAttrValueLater(new_event_callback_struct).start();
        }
        return eventId;
    }