RN若要調(diào)用js,先通過
(mReactContext.getJSModule(NativeToJsBridge.class)得到Js模塊母怜。
這一步最后調(diào)用的是com.facebook.react.bridge.JavaScriptModuleRegistry#getJavaScriptModule
實(shí)際上,這個(gè)函數(shù)里面是new了一個(gè)代理對(duì)象
JavaScriptModule interfaceProxy = (JavaScriptModule) Proxy.newProxyInstance(
? ? moduleInterface.getClassLoader(),
? ? new Class[]{moduleInterface},
? ? new JavaScriptModuleInvocationHandler(instance, moduleInterface));
當(dāng)調(diào)用代理對(duì)象對(duì)應(yīng)js方法的時(shí)候妥箕,走到
com.facebook.react.bridge.JavaScriptModuleRegistry.JavaScriptModuleInvocationHandler#invoke:(這個(gè)過程是java 動(dòng)態(tài)代理的原理笙隙。)
@Override
public @Nullable Object invoke(Object proxy, Method method, @Nullable Object[] args) throws Throwable {
? NativeArray jsArgs = args != null
? ? ? Arguments.fromJavaArgs(args)
? ? : new WritableNativeArray();
? mCatalystInstance.callFunction(getJSModuleName(), method.getName(), jsArgs);
? return null;
}
? mCatalystInstance.callFunction(getJSModuleName(), method.getName(), jsArgs);這一句調(diào)用的是:
com.facebook.react.bridge.CatalystInstanceImpl#callFunction(com.facebook.react.bridge.CatalystInstanceImpl.PendingJSCall)
public void callFunction(PendingJSCall function) {
? if (mDestroyed) {
? ? final String call = function.toString();
? ? FLog.w(ReactConstants.TAG, "Calling JS function after bridge has been destroyed: " + call);
? ? return;
? }
? if (!mAcceptCalls) {
? ? // Most of the time the instance is initialized and we don't need to acquire the lock
? ? synchronized (mJSCallsPendingInitLock) {
? ? ? if (!mAcceptCalls) {
? ? ? ? mJSCallsPendingInit.add(function);
? ? ? ? return;
? ? ? }
? ? }
? }
? function.call(this);
}
? function.call(this);也就是:
com.facebook.react.bridge.CatalystInstanceImpl.PendingJSCall#call
void call(CatalystInstanceImpl catalystInstance) {
? NativeArray arguments = mArguments != null ? mArguments : new WritableNativeArray();
? catalystInstance.jniCallJSFunction(mModule, mMethod, arguments);
}
最后調(diào)用到了jni:catalystInstance.jniCallJSFunction(mModule, mMethod, arguments);
該jni函數(shù)在:
ReactAndroid/src/main/jni/react/jni/CatalystInstanceImpl.cpp:
void CatalystInstanceImpl::jniCallJSFunction(std::string module, std::string method, NativeArray* arguments) {
? // We want to share the C++ code, and on iOS, modules pass module/method
? // names as strings all the way through to JS, and there's no way to do
? // string -> id mapping on the objc side.? So on Android, we convert the
? // number to a string, here which gets passed as-is to JS.? There, they they
? // used as ids if isFinite(), which handles this case, and looked up as
? // strings otherwise.? Eventually, we'll probably want to modify the stack
? // from the JS proxy through here to use strings, too.
? instance_->callJSFunction(std::move(module),
? ? ? ? ? ? ? ? ? ? ? ? ? ? std::move(method),
? ? ? ? ? ? ? ? ? ? ? ? ? ? arguments->consume());
}
?instance_->callJSFunctio? ?這一句調(diào)用的是:
ReactCommon/cxxreact/Instance.cpp:
void Instance::callJSFunction(std::string &&module, std::string &&method,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? folly::dynamic &¶ms) {
? callback_->incrementPendingJSCalls();
? nativeToJsBridge_->callFunction(std::move(module), std::move(method),
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? std::move(params));
}
nativeToJsBridge_->callFunction 這一句是:
ReactCommon/cxxreact/NativeToJsBridge.cpp:
void NativeToJsBridge::callFunction(
? ? std::string&& module,
? ? std::string&& method,
? ? folly::dynamic&& arguments) {
? int systraceCookie = -1;
? #ifdef WITH_FBSYSTRACE
? systraceCookie = m_systraceCookie++;
? FbSystraceAsyncFlow::begin(
? ? ? TRACE_TAG_REACT_CXX_BRIDGE,
? ? ? "JSCall",
? ? ? systraceCookie);
? #endif
? runOnExecutorQueue([this, module = std::move(module), method = std::move(method), arguments = std::move(arguments), systraceCookie]
? ? (JSExecutor* executor) {
? ? ? if (m_applicationScriptHasFailure) {
? ? ? ? LOG(ERROR) << "Attempting to call JS function on a bad application bundle: " << module.c_str() << "." << method.c_str() << "()";
? ? ? ? throw std::runtime_error("Attempting to call JS function on a bad application bundle: " + module + "." + method + "()");
? ? ? }
? ? ? #ifdef WITH_FBSYSTRACE
? ? ? FbSystraceAsyncFlow::end(
? ? ? ? ? TRACE_TAG_REACT_CXX_BRIDGE,
? ? ? ? ? "JSCall",
? ? ? ? ? systraceCookie);
? ? ? SystraceSection s("NativeToJsBridge::callFunction", "module", module, "method", method);
? ? ? #endif
? ? ? // This is safe because we are running on the executor's thread: it won't
? ? ? // destruct until after it's been unregistered (which we check above) and
? ? ? // that will happen on this thread
? ? ? executor->callFunction(module, method, arguments);
? ? });
}
?executor->callFunction 實(shí)際上調(diào)用的是:
ReactCommon/cxxreact/JSCExecutor.cpp
void JSCExecutor::callFunction(
? ? const std::string& moduleId,
? ? const std::string& methodId,
? ? const folly::dynamic& arguments) {
? SystraceSection s("JSCExecutor::callFunction");
? // This weird pattern is because Value is not default constructible.
? // The lambda is inlined, so there's no overhead.
? auto result = [&] {
? ? JSContextLock lock(m_context);
? ? try {
? ? ? if (!m_callFunctionReturnResultAndFlushedQueueJS) {
? ? ? ? bindBridge();
? ? ? }
? ? ? return m_callFunctionReturnFlushedQueueJS->callAsFunction(
? ? ? ? ? {Value(m_context, String::createExpectingAscii(m_context, moduleId)),
? ? ? ? ? Value(m_context, String::createExpectingAscii(m_context, methodId)),
? ? ? ? ? Value::fromDynamic(m_context, std::move(arguments))});
? ? } catch (...) {
? ? ? std::throw_with_nested(
? ? ? ? ? std::runtime_error("Error calling " + moduleId + "." + methodId));
? ? }
? }();
? callNativeModules(std::move(result));
}
到這里基本就結(jié)束了,通過m_callFunctionReturnFlushedQueueJS->callAsFunction來執(zhí)行js函數(shù)毅访。
我們順便跟一下m_callFunctionReturnFlushedQueueJS是怎么來的
m_callFunctionReturnFlushedQueueJS->callAsFunction(
? ? {Value(m_context, String::createExpectingAscii(m_context, moduleId)),
? ? Value(m_context, String::createExpectingAscii(m_context, methodId)),
? ? Value::fromDynamic(m_context, std::move(arguments))});
這一句的m_callFunctionReturnFlushedQueueJS是:
m_callFunctionReturnFlushedQueueJS =
? ? batchedBridge.getProperty("callFunctionReturnFlushedQueue").asObject();
這個(gè)就是操作Js對(duì)象了。
上面的batchedBridge來自batchedBridgeValue:
auto batchedBridge = batchedBridgeValue.asObject();
而batchedBridgeValue是:
auto batchedBridgeValue = global.getProperty("__fbBatchedBridge");
if (batchedBridgeValue.isUndefined()) {
? auto requireBatchedBridge =
? ? ? global.getProperty("__fbRequireBatchedBridge");
? if (!requireBatchedBridge.isUndefined()) {
? ? batchedBridgeValue = requireBatchedBridge.asObject().callAsFunction({});
? }
? if (batchedBridgeValue.isUndefined()) {
? ? throw JSException(
? ? ? ? "Could not get BatchedBridge, make sure your bundle is packaged correctly");
? }
這里的global是:
auto global = Object::getGlobalObject(m_context);
而m_context是:
m_context =
? ? JSC_JSGlobalContextCreateInGroup(useCustomJSC, nullptr, globalClass);
JSC_JSGlobalContextCreateInGroup這個(gè)是:
#define JSC_JSGlobalContextCreateInGroup(...) __jsc_bool_wrapper(JSGlobalContextCreateInGroup, __VA_ARGS__)
從這里就可以看到m_context是通過jscore的api:JSGlobalContextCreateInGroup獲取的對(duì)象了盘榨。