JS-Native Communication

JS to Native Messaging

JS to native messaging requires the TurboModule module. If you want to implement your own TurboModule, refer to Custom TurboModule.

Native to JS Messaging

DeviceEventEmitter

ArkTS Invocation

Native to JS messaging is implemented through DeviceEventEmitter to send events to the JS side. This includes two parts: native side sending events and JS side listening for events. This section describes the flow of native sending messages to JS.

  1. Native side sending event

    Developers can call emitDeviceEvent in RNInstance to send custom events to the JS side. The first parameter is the event name, the second parameter is the event data.

    // SampleApp\entry\src\main\ets\customView\MarqueeView.ets
    this.ctx.rnInstance.emitDeviceEvent("clickMarqueeEvent", { params: { age: 18 } })
    
  2. JS side listening for event

    Developers need to add corresponding event listeners and handlers in JS code.

    DeviceEventEmitter.addListener('clickMarqueeEvent', e => {
      // Add event handling
    });
    

C++ Invocation

C++ components can use TurboModule::emitDeviceEvent to send events.

For example, sending an onAnimatedValueUpdate event with two properties named "tag" and "value".

The setProperty method includes three parameters:

  • runtime: facebook::jsi::Runtime object
  • tag: property name
  • value: property value
this->emitDeviceEvent(
  rt,
  "onAnimatedValueUpdate",
  [tag, value](jsi::Runtime& rt, std::vector<jsi::Value>& args) {
    auto payload = jsi::Object(rt);
    payload.setProperty(rt, "tag", tag);
    payload.setProperty(rt, "value", value);
    args.push_back(std::move(payload));
  });    

emitComponentEvent

Besides DeviceEventEmitter, you can also use emitComponentEvent.

ArkTS Invocation

this.ctx.rnInstance.emitComponentEvent(tag: Tag, eventName: string, payload: any)

This method includes three parameters:

  • tag: node
  • eventName: method name to call
  • payload: parameters to pass

C++ Invocation

C++ components can use the member m_eventEmitter inherited from parent class CppComponentInstance to send events.

For example, sending a load event with a "source" object: "source" has three properties named "width", "height", "uri";

The setProperty method includes three parameters:

  • runtime: facebook::jsi::Runtime object
  • name: property name
  • value: property value
m_eventEmitter->dispatchEvent("load", [=](facebook::jsi::Runtime& runtime) {
  auto payload = facebook::jsi::Object(runtime);
  auto source = facebook::jsi::Object(runtime);
  source.setProperty(runtime, "width", width);
  source.setProperty(runtime, "height", height);
  source.setProperty(runtime, "uri", uri.c_str());
  return payload;
});

callRNFunction

Besides DeviceEventEmitter, you can also use callRNFunction.