Interface.js
1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { JsInterfaces } from '@/api/NativeApis'
class Interface {
constructor(interfaces) {
this.listeners = {}
this.__init(interfaces)
}
on(methodName, callback) {
this.listeners[methodName] = callback
}
call(nativeMethod, data, isback) {
if (isback) {
return this.__callNativeApiBack(nativeMethod, data)
}
return this.__callNativeApiBack(nativeMethod, data)
}
__init(interfaces = []) {
interfaces.forEach(methodName => {
this[methodName] = (data) => {
this.listeners[methodName](data ? JSON.parse(data) : data)
}
});
}
__callNativeApiNotBack(nativeMethod, data) {
try {
if (that.__callNativeApi(nativeMethod, { data })) {
return Promise.reject(`无效调用:[${nativeMethod}]`)
}
return Promise.resolve()
} catch (e) {
return Promise.reject(`接口调用异常:[${nativeMethod}]`)
}
}
__callNativeApiBack(nativeMethod, data) {
const that = this
const jsMethodName = `js${Date.now()}`
return new Promise((resolve, reject) => {
try {
that[jsMethodName] = (data) => {
resolve(data ? JSON.parse(data) : data)
delete that[jsMethodName]
}
if (that.__callNativeApi(nativeMethod, { data, jsMethodName })) {
return reject(`无效调用:[${nativeMethod}]`)
}
} catch (e) {
return Promise.reject(`接口调用异常:[${nativeMethod}]`)
}
})
}
__callNativeApi(nativeMethod, data) {
if (window.$NativeApi || $NativeApi[nativeMethod]) {
window.$NativeApi[nativeMethod](JSON.stringify(data))
} else {
return true
}
}
}
window.$api = new Interface(JsInterfaces)