HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Simple event system

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
systemsimpleevent

Problem

This is a class which provides a simple event system mechanism:

template 
class EventChannel
{
private:
    using idType = unsigned int;
    static idType& getId()
    {
        static idType id = 0;
        return id;
    }

    static std::unordered_map>& getHandlers()
    {
        static std::unordered_map> handlers;
        return handlers;
    }
public:
    static idType regiterListener(std::function listener)
    {
        auto& id = getId();
        id++;
        getHandlers()[id] = listener;
        return id;
    }
    static void tringgerEvent(T e)
    {
        for (const auto& h : getHandlers())
        {
            h.second(e);
        }
    }
    static void removeListener(idType listener_id)
    {
        getHandlers().erase(listener_id);
    }
};


and the usage is like this:

struct TouchEvent
{
    int t_id;
    float x;
    float y;
};
//just for convenience
template 
void DISPATCH_EVENT(T t)
{
    EventChannel::tringgerEvent(t);
}
...

auto lid = EventChannel::regiterListener([](TouchEvent ev)->bool
{
    cout << "got touch " << ev.t_id << "\n"; return false; 
});

DISPATCH_EVENT(TouchEvent{ 10, 2, 4 });


The output would be just as you would expect:

got touch 10


It's also possible to remove the previously set listener:

EventChannel::removeListener(lid);


Any insight on what I've done badly wrong would be much appreciated.

Solution

Your code looks very good to me. The only thing I would recommend changing is getId(). The fact that the function holds a static variable that is changed in regiterListener violates encapsulation a little bit. I would change it to:

static idType getNextId()
{
    static idType id = 0;
    return ++id;
}


and use it as:

static idType regiterListener(std::function listener)
{
    auto id = getNextId();
    getHandlers()[id] = listener;
    return id;
}

Code Snippets

static idType getNextId()
{
    static idType id = 0;
    return ++id;
}
static idType regiterListener(std::function<bool(T)> listener)
{
    auto id = getNextId();
    getHandlers()[id] = listener;
    return id;
}

Context

StackExchange Code Review Q#127171, answer score: 2

Revisions (0)

No revisions yet.