inteface.js 1.53 KB

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()