Search code examples
c++c++11wxwidgets

Unbinding a lambda event handler


How can I unbind an event handler which I've bind as shown below?

MyFrame::MyFrame()
{
    Bind(wxEVT_COMMAND_MENU_SELECTED,
         [](wxCommandEvent&) {
            // Do something useful
         },

         wxID_EXIT);
}

Many thanks for the first answer. I've added some additional information.

The possibility to unbind an event handler by using a concrete Functor is documented and works fine, but if you use the C++ 11 lambda style to bind somthing, later there is no Functor availibale to call the unbind method. And this causes trouble if the corresponding wxEvtHandler should by destroied.

Is there a "trick". . . if not I don't see a real use case to bind by using lambda functors. Hopefully I'm wrong . . .

Many thanks
Hacki


Solution

  • You can't unbind when the call to Bind has a lambda, as your example. If you store the lambda, then you can unbind from that, e.g.

    class MyFrame 
    { 
        ... 
        std::function<void()> DoUnbind;
    }
    
    MyFrame::MyFrame()
    {
        auto DoSomethingUseful = [](wxCommandEvent&) {
                // Do something useful
             };
    
        Bind(wxEVT_COMMAND_MENU_SELECTED,
             DoSomethingUseful,
             wxID_EXIT);
    
        DoUnbind = [DoSomethingUseful](){
            Unbind(wxEVT_COMMAND_MENU_SELECTED,
                   DoSomethingUseful,
                   wxID_EXIT);
        };
    }