Skip to content

Commit

Permalink
feat(Wechat): 支持延后 config
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Mar 30, 2019
1 parent 3fb0efc commit 99e5cd6
Showing 1 changed file with 21 additions and 14 deletions.
35 changes: 21 additions & 14 deletions src/Wechat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,37 +154,30 @@ export class WeChat {
private ready: boolean = false

private bus = new EventBus<{
ready: () => void,
error: WechatErrorCallback,
}>()

private prevShareParams: WechatUpdateShareDataParams = {}

constructor(params: WechatConfigParams) {
constructor(params?: WechatConfigParams) {
this.config(params)
}

config(params: WechatConfigParams) {
if (typeof wx === 'undefined') {
throw new Error('请先引入微信 JSSDK')
}
wx.config(params)
wx.ready(() => {
this.ready = true
this.bus.emit('ready')
})
wx.error((err: any) => {
this.bus.emit('error', err)
})
}

private invoke(jsApi: WechatJsApi, params: Record<string, any> = {}): Promise<any> {
return new Promise((resolve, reject) => {
if (!wx[jsApi]) reject(`wx.${jsApi} 不可用`)
params.success = resolve
params.fail = reject
if (this.ready) {
wx[jsApi](params)
} else {
wx.ready(() => wx[jsApi](params))
}
})
}

checkJsApi<T extends WechatJsApi>(jsApiList: T[]): Promise<Record<T, boolean>> {
return this.invoke('checkJsApi', { jsApiList })
.then(res => res.checkResult)
Expand Down Expand Up @@ -245,4 +238,18 @@ export class WeChat {
onError(callback: WechatErrorCallback) {
this.bus.on('error', callback)
}

private invoke(jsApi: WechatJsApi, params: Record<string, any> = {}): Promise<any> {
return new Promise((resolve, reject) => {
if (typeof wx === 'undefined') return reject('请先引入微信 JSSDK')
if (!wx[jsApi]) return reject(`wx.${jsApi} 不可用`)
params.success = resolve
params.fail = reject
if (this.ready) {
wx[jsApi](params)
} else {
this.bus.once('ready', () => wx[jsApi](params))
}
})
}
}

0 comments on commit 99e5cd6

Please sign in to comment.