Skip to content

Instantly share code, notes, and snippets.

@chunkyguy
Created March 27, 2013 12:08
Show Gist options
  • Save chunkyguy/5253727 to your computer and use it in GitHub Desktop.
Save chunkyguy/5253727 to your computer and use it in GitHub Desktop.
This code demonstrates a way to broadcast messages to many listeners. I'm scrapping this code I worked on for few hours. Why? Because for now I'm going forward with one global event dispatcher. Right now on iDevices it doesn't makes any sense to buffer the events, as the OS already buffers them. Maybe someday I'll return to something similar.
//
// EventLoop.h
// HideousGameEngine
//
// Created by Sid on 27/03/13.
// Copyright (c) 2013 whackylabs. All rights reserved.
//
#ifndef __HideousGameEngine__EventLoop__
#define __HideousGameEngine__EventLoop__
#include <list>
#include <algorithm>
#include "Gesture.h"
namespace he{
template<typename T>
class Listener_equal;
template<typename T>
class Listener_exec;
template<typename T>
class Listener{
public:
typedef void (T::*callback)(Gesture g);
Listener(T &o, callback cb) : object(o), callb(cb){}
private:
T object;
callback callb;
friend class Listener_equal<T>;
friend class Listener_exec<T>;
};
template<typename T>
class Listener_equal{
Listener_equal(std::list<Listener<T>> &ll) : l(ll) {}
bool operator()(Listener<T> obj){
for(typename std::list<Listener<T>>::iterator it = l.begin(); it != l.end(); ++it){
return (it->object == obj);
}
}
private:
std::list<Listener<T>> &l;
};
template<typename T>
class Listener_exec{
public:
Listener_exec(Gesture gg) : g(gg) {}
void operator()(Listener<T> &l){
l.object.*callb(g);
}
private:
Gesture g;
};
template<typename T>
class EventLoop{
public:
EventLoop();
static EventLoop &instance(){
static EventLoop el;
return el;
}
void addListener(Listener<T> l){
new_Listeners.push_back(l);
}
void removeListener(Listener<T> l){
dead_Listeners.push_back(l);
}
void update(double dt){
//remove dead
if(!dead_Listeners.empty()){
Listener_equal<T> leq(dead_Listeners);
active_Listeners.remove_if(leq);
dead_Listeners.clear();
}
//add new
if(!new_Listeners.empty()){
active_Listeners.splice(active_Listeners.end(), new_Listeners);
new_Listeners.clear();
}
//run
Listener_exec<T> lex(g);
std::for_each(active_Listeners.begin(), active_Listeners.end(), lex);
}
private:
std::list<Listener<T>> active_Listeners;
std::list<Listener<T>> dead_Listeners;
std::list<Listener<T>> new_Listeners;
Gesture g;
};
}
#endif /* defined(__HideousGameEngine__EventLoop__) */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment