inteface.js
1.53 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
const NativeInteface = [
'callNativePay',
'callNativeShare',
'callNativeAppInfo',
'callNativeCamera',
'callNativeAlbum',
'callNativeUpdate',
'callNativeMobile'
]
const JsInteface = [
'payResult',
'shareResult',
'photoResult',
'appInfoResult'
]
class Inteface {
constructor() {
this.listeners = {}
this.__init()
}
on (methodName, callback) {
this.listeners[methodName] = callback
}
__init () {
NativeInteface.forEach(methodName => {
this[methodName] = (data, jsMethodName, callback) => {
try {
if (jsMethodName) {
this.listeners[jsMethodName] = callback
}
const json = JSON.stringify(jsMethodName && { jsMethodName, data } || { data })
if (window.$NativeApi) {
window.$NativeApi[methodName](json)
} else if (window.webkit) {
window.webkit.messageHandlers[methodName](json)
}
} catch (e) {
callback && callback()
console.warn("===========无效,非内置调用", methodName);
}
}
})
JsInteface.forEach(methodName => {
this[methodName] = (data) => {
const objValue = data ? JSON.parse(data) : data
this.listeners[methodName](objValue)
}
})
}
}
window.$api = new Inteface()