Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

listening to multiple events with one listener?

Tags:

I'm building an app in Symfony2 that has a social-driven aspect (many actions a user performs on the site will show up in a "news feed"-style list for others to view). I've determined that the sf2 event dispatcher/listener system is the best way to handle this, but I've run into something of a snag in trying to configure my listener to handle many different events.

The (now outdated) documentation I've found in my searches seems to indicate that at one point, event listeners could register on multiple events, but the code has been refactored, and now the configuration looks something like this:

config.yml:

services:   social.listener:     class: F\Q\C\N\SocialEventListener     tags:       - { name: kernel.listener, event: onSocialShare } 

Is there any way to either:

  1. Easily pass multiple events (something like event: [onSocialShare, onSocialFriend, onSocialCreate] works, but that feels like it will quickly get ugly and unmaintainable, clogging up my config file with potentially dozens of social events
  2. Define the event to which I want to subscribe from code (as was done previously)
  3. Or possibly another, better option that I haven't thought of yet

Thanks in advance.

like image 713
Derek Stobbe Avatar asked May 09 '11 17:05

Derek Stobbe


People also ask

Can you add multiple events to event listener?

We can add multiple event listeners for different events on the same element. One will not replace or overwrite another. In the example above we add two extra events to the 'button' element, mouseover and mouseout.

Can you call multiple functions with event listener?

We can invoke multiple functions on a single event listener without overwriting each other. To do this we simply call the addEventListener() method more than once with a different function. In the example above, we add another event listener for the same event on the same button.

Can you have multiple event handlers?

Only one event handler can be assigned for every event in an element. If needed the handler can be replaced by assigning another function to the same property. Below we show how to set a simple greet() function for the click event using the onclick property.


1 Answers

Word back from the symfony-users google group (thread here) is that the appropriate way to do this is by adding several tags:

services:   social.listener:     class: F\Q\C\N\SocialEventListener     tags:       - { name: kernel.listener, event: onSocialShare }       - { name: kernel.listener, event: onSocialFriend }       - { name: kernel.listener, event: ... etc } 

So, it looks like currently, there is no good way of adding event subscriptions from listener code. Oh well.

like image 168
Derek Stobbe Avatar answered Sep 19 '22 13:09

Derek Stobbe