I’m making a simple button class for the Iphone.
I’m using an event to execute a method inside of testApp.
I have a cout statement inside of this method but it gets sent three times when I click on my button.
I must be doing something wrong.
my class code looks something like this:
class Button{
public:
ofEvent triggerEvent;
}
Button::TouchDown(ofTouchEvenrArgs &touch){
if(rect.inside(touch.x, touch.y)){
ofNotifyEvent(triggerEvent);
}
}
inside of testApp I add the listener this way
testApp.h :
Button myButton;
void myButtonPressed();
testApp.mm:
ofAddListener(myButton.triggerEvent, this, &testApp::myButtonPressed);
void testApp::myButtonPressed(){
cout << “my button was pressed” << endl;
}
console output when clicked once:
my button was pressed
my button was pressed
my button was pressed
I’m sorry if the error I’m doing seems obvious, Im not yet very familiar with the Listener pattern yet thank you for your understanding!
I found my error…I was making a loophole of events by passing down touch events while my class was already registering the touch event inside of itself.
Instead i declared addListener/removeListener fonctions as members of my button class as follow:
template<class ListenerClass, typename ListenerMethod>
void addListener(ListenerClass * listener, ListenerMethod method){
ofAddListener(triggerEvent,listener,method);
}
template<class ListenerClass, typename ListenerMethod>
void removeListener(ListenerClass * listener, ListenerMethod method){
ofRemoveListener(triggerEvent,listener,method);
}
in my testApp’s setup
I simply call
myButton.addlistener(…)
instead of ofAddListener(my button.event…)
Inside of my button class’s setup function I’m enabling the registering of touch events so I dont need to make an actual call inside of my testApp::touchUp section in the following fashion to pass down the touch events :
void testApp::touchUp(touchEventsArgs & touch){
myButton.touchUp(touch);
}
Now I can remove the myButton.touchUp(touch); and my events gets triggered inside of my object.
The cout command now gets triggered only once which is really good since now I can have a custom function executed outside of the app’s main section when the associated button is pressed.
This is great news since, I’ve been looking for a way to do this for ages. 