Commit 2c95129f authored by hewenhao's avatar hewenhao

feat: native bridge 支持监听多个事件

parent ab937710
...@@ -37,14 +37,30 @@ const sendNativeMessage = (data: { type: string; data: any }) => { ...@@ -37,14 +37,30 @@ const sendNativeMessage = (data: { type: string; data: any }) => {
window.ReactNativeWebView.postMessage(JSON.stringify(data)); window.ReactNativeWebView.postMessage(JSON.stringify(data));
}; };
type ListenerType = (this: ComponentInternalInstance | null, ...arg: any[]) => any;
function useNativeBridge( function useNativeBridge(
eventType: string, eventType: string,
listener: (this: ComponentInternalInstance | null, ...arg: any[]) => any listener: ListenerType
): [typeof sendNativeMessage, typeof eventBus];
function useNativeBridge(eventMap: {
[key: string]: ListenerType;
}): [typeof sendNativeMessage, typeof eventBus];
function useNativeBridge(
eventTypeOrEventMap: string | { [key: string]: ListenerType },
listener?: ListenerType
): [typeof sendNativeMessage, typeof eventBus] { ): [typeof sendNativeMessage, typeof eventBus] {
const _listener = function(this: ComponentInternalInstance | null, arg?: NativeInvokeFuncParams) { const _listener = function(this: ComponentInternalInstance | null, arg?: NativeInvokeFuncParams) {
if (!arg) return; if (!arg) return;
if (eventType === arg.method) { const { method, data } = arg;
listener.apply(this, [arg.data]); if (typeof eventTypeOrEventMap === "string") {
if (eventTypeOrEventMap === method && listener) {
listener.apply(this, [data]);
}
} else if (typeof eventTypeOrEventMap[method] === "function") {
eventTypeOrEventMap[method].apply(this, [data]);
} }
}; };
......
...@@ -7,13 +7,18 @@ ...@@ -7,13 +7,18 @@
import { ref } from "vue"; import { ref } from "vue";
import { useNativeBridge } from "@/util/use-native-bridge"; import { useNativeBridge } from "@/util/use-native-bridge";
const [sendNativeMessage, eventBus] = useNativeBridge("bindWechatChange", function(arg) { const [sendNativeMessage, eventBus] = useNativeBridge({
console.log(this, arg); onBindWechatChange(arg) {
console.log(this, arg);
}
});
useNativeBridge("onBindWechatChange", function(arg) {
console.log(this, arg, "bb");
}); });
const count = ref(1000); const count = ref(1000);
const emitTest = () => { const emitTest = () => {
eventBus.emit("GEEK_NATVIE_NAME", { eventBus.emit("GEEK_NATVIE_NAME", {
method: "bindWechatChange", method: "onBindWechatChange",
data: { data: {
hhh: 13213 hhh: 13213
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment