AsyncCallback

Hello!

It's been a while since I shared some code, so I figured I'd start posting some of the useful things I've accumulated over the last few years. 

I'll start simple, with this helper template...


///////////////////////////////////////////////////////////////////////////////
/**
    Handy object to wrap a member function with an AsyncUpdater, providing an 
    easy way to implement multiple asynchronous callbacks (when you can't be
    bothered writing any auxilliary message classes!).

    e.g. 
    class MyClass
    {
        AsyncCallback< MyClass > notifier;
    public:
        
        MyClass () : notifier (*this, &MyClass::notified)
        {
            notifier.trigger ();
        }

        void notified ()
        {
            // called asynchronously after constructor
        }
    };
*/
///////////////////////////////////////////////////////////////////////////////
template <class OwnerClass>
class AsyncCallback :   private AsyncUpdater
{
    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(AsyncCallback);
public:
    
    typedef void (OwnerClass::*CallbackFunction) ();
    AsyncCallback (OwnerClass& ownerInstance, CallbackFunction functionToCall)
    :   owner (ownerInstance),
        function (functionToCall)
    {
    }
    
    ~AsyncCallback ()
    {
        cancel ();
        function = nullptr; // Mark as invalid to avoid further triggers during destruction
    }
    
    void cancel ()
    {
        cancelPendingUpdate ();
    }
    
    void trigger ()
    {
        if (function != nullptr)
        {
            triggerAsyncUpdate ();
        }
    }
    
    void triggerSynchronously ()
    {
        if (function != nullptr)
        {
            cancel ();
            handleAsyncUpdate ();
        }
    }
    
    void handleAsyncUpdate () override
    {
        if (function != nullptr)
        {
            (owner.*(function)) ();
        }
    }
    
private:
    
    OwnerClass& owner;
    CallbackFunction function;
};
///////////////////////////////////////////////////////////////////////////////

Good stuff.

Now that most people have got C++11 compilers it might be interesting to start playing around with lambdas to do this kind of thing too.