Skip to content

Commit

Permalink
refactor(UniApp): 优化 eventBus
Browse files Browse the repository at this point in the history
  • Loading branch information
zhenyuWang committed Sep 4, 2024
1 parent ae120fe commit 555024d
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 37 deletions.
22 changes: 4 additions & 18 deletions packages/uni-app-plus/src/x/framework/app/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,32 +16,18 @@ import { initService } from './initService'
import { setNativeApp } from './app'
import { initComponentInstance } from './initComponentInstance'
import type {
EventBus,
NavigateToOptions,
SwitchTabOptions,
} from '@dcloudio/uni-app-x/types/uni'
import { UniEventBus } from '@dcloudio/uni-api'
import type { UniApp } from '@dcloudio/uni-app-x/types/app'
import { EventBus } from '@dcloudio/uni-api'

let appCtx: ComponentPublicInstance
const defaultApp = {
globalData: {},
}

class UniApp implements EventBus {
private $eventBus = new UniEventBus()
on = (eventName: string, callback: Function) => {
this.$eventBus.on(eventName, callback)
}
once = (eventName: string, callback: Function) => {
this.$eventBus.once(eventName, callback)
}
off = (eventName?: string, callback?: Function | null) => {
this.$eventBus.off(eventName, callback)
}
emit = (eventName: string, ...args: any[]) => {
this.$eventBus.emit(eventName, ...args)
}

class UniAppImpl extends EventBus implements UniApp {
get vm() {
return appCtx
}
Expand All @@ -53,7 +39,7 @@ class UniApp implements EventBus {
}
}

let $uniApp = new UniApp()
let $uniApp = new UniAppImpl()

export const entryPageState = {
isReady: false,
Expand Down
23 changes: 4 additions & 19 deletions packages/uni-h5/src/framework/setup/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,28 +7,13 @@ import {
initService,
initView,
} from '@dcloudio/uni-core'
import { UniEventBus } from '@dcloudio/uni-api'
import type { EventBus } from '@dcloudio/uni-app-x/types/uni'
import { EventBus } from '@dcloudio/uni-api'
import type { UniApp } from '@dcloudio/uni-app-x/types/app'

let appVm: ComponentPublicInstance
// @ts-expect-error
let $uniApp: UniApp
if (__X__) {
class UniApp implements EventBus {
private $eventBus = new UniEventBus()
on = (eventName: string, callback: Function) => {
this.$eventBus.on(eventName, callback)
}
once = (eventName: string, callback: Function) => {
this.$eventBus.once(eventName, callback)
}
off = (eventName?: string, callback?: Function | null) => {
this.$eventBus.off(eventName, callback)
}
emit = (eventName: string, ...args: any[]) => {
this.$eventBus.emit(eventName, ...args)
}

class UniAppImpl extends EventBus implements UniApp {
get vm() {
return appVm
}
Expand All @@ -39,7 +24,7 @@ if (__X__) {
return appVm?.globalData || {}
}
}
$uniApp = new UniApp()
$uniApp = new UniAppImpl()
}

export function getApp() {
Expand Down

0 comments on commit 555024d

Please sign in to comment.