Last active
December 14, 2015 00:39
-
-
Save jkosoy/5000041 to your computer and use it in GitHub Desktop.
Processing example of event dispatching.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ExampleDispatcher { | |
private Object _listener; | |
public void setListener(Object obj) { | |
_listener = obj; | |
} | |
public void dispatchBasic() { | |
try { | |
Method callback = _listener.getClass().getMethod("handleBasicEvent"); | |
callback.invoke(_listener); // calls the method with itself as the scope. _listener should always be the first argument. | |
} | |
catch(Exception e) { | |
// the listener probably doesn't have void basicEventHandler(); | |
} | |
} | |
public void dispatchWithArguments() { | |
try { | |
// in order to find the correct method we have to specify that we're looking for a method named "handleEventWithArgs" | |
// that accepts two arguments: one of type int, one of type float. here's how we do that. | |
Method callback = _listener.getClass().getMethod("handleEventWithArgs",int.class,float.class); | |
// we know our listener must be the first argument from our basic example. | |
callback.invoke(_listener,1,3.14); | |
} | |
catch(Exception e) {} | |
} | |
public void dispatchAddOneToNumber() { | |
try { | |
Method callback = _listener.getClass().getMethod("addOne",int.class); | |
Object invokedResult = callback.invoke(_listener,1); // always returns type Object. We can cast from there. | |
int total = (int) invokedResult; | |
println("The total is :: " + total); | |
} | |
catch(Exception e) { | |
} | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ExampleDispatcher myDispatcher; | |
void setup() { | |
myDispatcher = new ExampleDispatcher(); | |
myDispatcher.setListener(this); | |
myDispatcher.dispatchBasic(); | |
myDispatcher.dispatchWithArguments(); | |
myDispatcher.dispatchAddOneToNumber(); | |
} | |
// a basic simple event. | |
void handleBasicEvent() { | |
println("A basic event!"); | |
} | |
// arguments will get passed from myDispatcher. | |
void handleEventWithArgs(int arg1,float arg2) { | |
println("arg1 is :: " + arg1 + " and arg2 is" + arg2); | |
} | |
// an example of communicating between the two. | |
int addOne(int num) { | |
return num+1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment