The reason Invoker is there is to avoid one extra if.
I've found myself often wanting to be able to parse a list of (potentially heterogeneous) collection of instances, and wanting to call a method on them. "Draw all Enemies", "update all Entities", "pause all Entities not related with the Pause menu".
Sometimes I knew there was a common method name that I could call ("update", or "draw"). Other times, I wanted to use a function - probably an anonymous function. For example, to pause all the entities not related with a menu, I might want to do this:
Code: Select all
if not relatedWithMenu(instance) then
I found out that I was doing "if type(method) == 'string' then method = instance[method] end" a bit too often, so I created the Invoker mixin to put it there.
Roland_Yonaba wrote:For instance, when I create a class, I do know what are its properties and methods, because i am the one who define them.
The case is simple when you phrase it like that.
Invoke is to be used with classes that you have *not* built. At least not in the context of what you are writing. This is useful when you are creating a library, and you don't really know what classes - or methods - it will be used with
The most obvious example (and the reason why I created the Invoker mixin in the first place) is the Apply mixin.
This mixin basically "insterts itself" between "new" and "initialize", and stores references to the newly created instances in a private _instances variable. Then you can do YourClass:apply(methodNameOrFunction, param1, param2 ...) and that will parse _instances applying the method to the lib. And you can pass a method name or a function, and it will work.
I hope this clarifies it a bit.