Interface.js 1.33 KB
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()