Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

 How to Invoke a JS API from C/C++

  • Pass the JS API function pointer to Native code and store it as a JSObjectRef
Code Block
JSObject.addEventListener(eventType, eventListener) //with eventListener having a definition like "function eventListener(event: any) {....}"
 
static JSValueRef addEventListener(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef *exception)
{
        JSObjectRef callbackObj = JSValueToObject(context, arguments[1], NULL);
 
        if (callbackObj != NULL && JSObjectIsFunction(context, callbackObj))
        {
              //Store the callbackObj in a variable
              eventListener = callbackObj;
              JSValueProtect(context, callbackObj);
        }
        else
        {
              return JSValueMakeUndefined(context);
        }
 
        return JSValueMakeNull(context);
}
  • To invoke the JS API from C/C++, call JSObjectCallAsFunction with the callbackObj and arguments

    Code Block
    JSObjectCallAsFunction(context, callbackObj, NULL, 1, args, NULL);  //args is the list of arguments if required