Invoking callback function

The documentation describes how to create a callback function object wrapper. The documentation I'm following comes from page 18 of the Monkey C Programmers Guide. It reads...

If you want to create a callback, you can create a Method object. Method objects are a combination of the function and the object instance or module they originate from. You can then call the method using the invoke method.

// Handle completion of long
function wakeMeUpBeforeYouGoGo() {
// Do something here
}

// Create a call back with the method method (jinx!)
doLongRunningTask(method(:wakeMeUpBeforeYouGoGo));



I've tried several times, and I'm unable to figure out what I need to do to be able to invoke the passed callback.

using Toybox.WatchUi as Ui;
using Toybox.System as Sys;

class TestView extends Ui.DataField {

function onLayout(dc) {
}

function onShow() {
}

function compute(info) {
}

function doLongRunningTask(fn) {
invoke(fn); // what to do here?
}

function wakeMeUpBeforeYouGoGo() {
Sys.println("!");
}

//! Update the view
function onUpdate(dc) {
doLongRunningTask(method(:wakeMeUpBeforeYouGoGo));
}
}
  • Nevermind. I figured it out. The method function creates a Toybox.Lang.Method object, which has an invoke() method on it. So the syntax to invoke the method object fn in the above example is...

    function doLongRunningTask(fn) {
    fn.invoke();
    }


    If you'd like to invoke the method with parameters, you just pass them to the invoke method, like this...

    fn.invoke(1);
    fn.invoke("Hello");
  • Former Member
    Former Member over 9 years ago
    Nevermind. I figured it out. The method function creates a Toybox.Lang.Method object, which has an invoke() method on it. So the syntax to invoke the method object fn in the above example is...

    function doLongRunningTask(fn) {
    fn.invoke();
    }


    If you'd like to invoke the method with parameters, you just pass them to the invoke method, like this...

    fn.invoke(1);
    fn.invoke("Hello");



    I've tried it, but it does not work. Error Message: "Could not find symbol method." in line "doLongRunningTask(method(:wakeMeUpBeforeYouGoGo));". What's going wrong??
  • It works just fine. There is something wrong with your code.

    Given the error message, the place that you are calling method is probably a context where there is no object (i.e., not a function of a class). In that case, you need to tell the system what object you want to invoke the function on by qualifying the call with an object reference (obj.method(:wakeMeUpBeforeYouGoGo) will create a Lang.Method that, when invoked, will call obj.wakeMeUpBeforeYouGoGo()).

    Travis
  • Former Member
    Former Member over 9 years ago
    Thank you very much! Your tip pointed me in the right direction. In my case it was a function of a module. A "new Lang.Method(ModuleName, :functionOfModul)" did the trick.