Interface.js
1.33 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
const NativeInterface = {
}
const JsInterface = {
}
class Interface {
constructor() {
this.listeners = {}
this.init()
}
on(methodName, callback) {
this.listeners[methodName] = callback
}
init() {
NativeInterface.forEach(methodName => {
this[methodName] = (data, jsMethodName, callback) => {
try {
if (jsMethodName) {
this.listeners[jsMethodName] = callback
}
const json = JSON.stringify(jsMethodName && { jsMethodName, data } || { data })
window.$NativeApi[methodName](json)
} catch (e) {
callback && callback()
console.log('-----无效,非内置调用', methodName)
}
}
})
JsInterface.forEach(methodName => {
this[methodName] = (data) => {
const objValue = data ? JSON.parse(data) : data
this.listeners[methodName](objValue)
}
})
}
CallNativeFun(type, data) {
try {
const json = JSON.stringify(data)
window.$NativeApi[type](json)
} catch (e) {
console.log('-----无效,非内置调用', type)
}
}
}
window.$api = new Interface()