std::function listeners for ofEvent + unregister token. Replaces #4392 #4774
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
ofEvent now supports adding std::function as a listener, that allows among other things:
For example to pass a lambda as a listener now you can do:
ofEvents().mouseMoved.newListener([](ofMouseEventArgs & mouse){ cout << mouse << endl; });Since std::function doesn't have an equality operator, there's no way to
unregister an event the old way calling
ofRemoveListener(function)sincethat required to compare the passed function with every other registered in
the event and remove it if it was the same.
ofRemoveListeneralso has some other problems, for example, the typical pattern:Has a problem with copy construction:
Won't be registered as listener and there won't be any compiler error.
Because of the rule of three
Any class that adds a listener in it's constructor and unregisters
in it's destructor. Needs also a copy constructor, operator=, and in
c++11 to be completely correct also a move constructor and an operator=
with move parameter.
With the new way of registering listeners one does:
The ofEventListener class unregisters the event automatically when it goes out
of scope avoiding the need for a destructor and because of that avoiding the
need for copy constructor...
Also since the class is not copyable if someone tries to copy an instance
of a class that contains an ofEventListener the compiler will give an error.
In any case the old method still works.