Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
React Native JSI Example
// This sample is a Work in Progress for JSI , and specific functions may change.
#pragma once
#include <string>
#include <unordered_map>
#include <jsi/jsi.h>
// This SameplJSIObject needs to inheric from HostObject, and this is the object that will be exposed to JS.
// From JS, we can call various methods or access properties on this object.
// Look at https://github.com/facebook/react-native/blob/master/ReactCommon/jsi/jsi.h for more details
class JSI_EXPORT SampleJSIObject : public facebook::jsi::HostObject {
public:
// STEP 1: Expose "window.__SampleJSIObject" to JavaScript.
// This is a static function, typically called from Java or ObjC when the application is initialized.
// In java, jsi::Runtime &runtime is basically catalystInstance.getJavaScriptContextHolder()
static void SampleJSIObject::install(jsi::Runtime &runtime) {
runtime.global().setProperty(
runtime,
"__sampleJSIObject",
jsi::Function::createFromHostFunction(
runtime,
jsi::PropNameID::forAscii(runtime, "__SampleJSIObject"),
1,
[binding](jsi::Runtime& rt, const jsi::Value& thisVal, const jsi::Value* args, size_t count) {
// Whenever someone accesses __SampleJSIObject, this is what gets exposed.
return std::make_shared<SampleJSIObject>();
}));
}
// This is like the getter. Any property or method access from JS goes through this method.
// For example, when we call window.__sampleJSIObject.method1(), this method is called
jsi::Value TurboModule::get(jsi::Runtime& runtime, const jsi::PropNameID& propName) {
std::string propNameUtf8 = propName.utf8(runtime);
// When window.__sampleJSIObject.method1() is called, propNameUtf8 == 'method1'
return jsi::Function::createFromHostFunction(
runtime,
propName, // Whats the name of the property that is called
argCount, // How many args does this method take
[](facebook::jsi::Runtime &rt, const facebook::jsi::Value &thisVal, const facebook::jsi::Value *args, size_t count) {
if (propNameUtf8 == 'method1') {
// Call a Java Method, that should be executed when window.__sampleJSIObject.method1() is called in JS.
// Note that we should convert jsi::Value *args to jni types
// The return type of Java Method should also be convereted back to jsi::Value
}
});
}
std::vector<PropNameID> getPropertyNames(Runtime& rt){
// Return a list of strings, that correspond to methods and properties
//
}
}
@prakashjais99

This comment has been minimized.

Copy link

@prakashjais99 prakashjais99 commented May 23, 2021

This Gist is very helpfull
How to create a simple emit and listener pattern like we have it normal react native module?

@huzaifaaak

This comment has been minimized.

Copy link

@huzaifaaak huzaifaaak commented May 25, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment