Created
November 2, 2021 14:01
-
-
Save mrousavy/0284fa637225fb63325231fecbd6b2f8 to your computer and use it in GitHub Desktop.
Notes from the JSI Consulting Session
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* jsi::Value | |
* - .asNumber() -> double | |
* - .asBoolean() -> bool | |
* - jsi::Value::undefined() | |
* - jsi::Value::null() | |
* - jsi::String | |
* - jsi::Symbol | |
* - jsi::Object | |
* - jsi::HostObject<T> | |
* - jsi::Function | |
* - jsi::HostFunction | |
* - jsi::Array | |
* - jsi::ArrayBuffer | |
*/ | |
jsi::Runtime& runtime; // TODO: Get actual runtime reference | |
// create a number | |
auto num = jsi::Value(42); | |
// create string | |
auto str = jsi::String::createFromUtf8("hello!", runtime); | |
// create an object | |
auto obj = jsi::Object(runtime); | |
obj.setProperty(runtime, "someNumber", num); | |
obj.setProperty(runtime, "someString", str); | |
// get a property from an object | |
jsi::Value num2 = obj.getProperty(runtime, "someNumber"); | |
// unboxing | |
bool isNumber = num2.isNumber(runtime); | |
if (isNumber) { | |
double actualNumber = num2.asNumber(); | |
} | |
// object unboxing | |
bool isObject = num2.isObject(runtime); | |
if (isObject) { | |
jsi::Object obj = num2.asObject(runtime); | |
bool isFunc = obj.isFunction(); | |
} | |
// create a host-function | |
auto sayHelloWorld = [](jsi::Runtime& runtime, | |
jsi::Value& thisValue, | |
jsi::Value* arguments, | |
size_t size) -> jsi::Value { | |
return jsi::Value::undefined(); | |
}; | |
auto func = jsi::Function::createFunctionFromHostFunction( | |
jsi::PropNameID::createPropNameIDFromString(runtime, "sayHelloWorld"), | |
std::move(sayHelloWorld), | |
0); | |
// call a (host)-function | |
func.call(runtime); | |
// inject any jsi::Value into the global namespace (JS world) | |
runtime.global().setProperty(runtime, "___sayHelloWorld", func); | |
// get any constructor | |
auto newPromise = runtime.global().getPropertyAsFunction(runtime, "Promise"); | |
auto promise = newPromise.callAsConstructor(runtime, /* (resolve, reject) => void */); | |
return promise; | |
// JS | |
global.___sayHelloWorld() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment