提交 fc19b233 编写于 作者: L Luc 提交者: Tim Neutkens

Replace event-emitter.js by mitt (#5987)

This PR aims at replacing next-server/lib/event-emitter.js by mitt.

Fix https://github.com/zeit/next.js/issues/4908

event-emitter.js is ~400 bytes gzipped vs mitt is 200 bytes
上级 f40ed302
export default class EventEmitter {
listeners = {}
on (event, cb) {
if (!this.listeners[event]) {
this.listeners[event] = new Set()
}
if (this.listeners[event].has(cb)) {
throw new Error(`Listener already exists for router event: \`${event}\``)
}
this.listeners[event].add(cb)
return this
}
emit (event, ...data) {
const listeners = this.listeners[event]
const hasListeners = listeners && listeners.size
if (!hasListeners) {
return false
}
listeners.forEach(cb => cb(...data)) // eslint-disable-line standard/no-callback-literal
return true
}
off (event, cb) {
this.listeners[event].delete(cb)
return this
}
}
/*
MIT License
Copyright (c) Jason Miller (https://jasonformat.com/)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// This file is based on https://github.com/developit/mitt/blob/v1.1.3/src/index.js
// It's been edited for the needs of this script
// See the LICENSE at the top of the file
type Handler = (...evts: any[]) => void
export default function mitt() {
const all: { [s: string]: Handler[] } = Object.create(null)
return {
on(type: string, handler: Handler) {
(all[type] || (all[type] = [])).push(handler)
},
off(type: string, handler: Handler) {
if (all[type]) {
// tslint:disable-next-line:no-bitwise
all[type].splice(all[type].indexOf(handler) >>> 0, 1)
}
},
emit(type: string, ...evts: any[]) {
(all[type] || []).slice().map((handler: Handler) => { handler(...evts) })
},
}
}
/* global __NEXT_DATA__ */ /* global __NEXT_DATA__ */
import { parse, format } from 'url' import { parse, format } from 'url'
import EventEmitter from '../event-emitter' import mitt from '../mitt'
import shallowEquals from './shallow-equals' import shallowEquals from './shallow-equals'
import { loadGetInitialProps, getURL } from '../utils' import { loadGetInitialProps, getURL } from '../utils'
export default class Router { export default class Router {
static events = new EventEmitter() static events = mitt()
constructor (pathname, query, as, { initialProps, pageLoader, App, Component, ErrorComponent, err } = {}) { constructor (pathname, query, as, { initialProps, pageLoader, App, Component, ErrorComponent, err } = {}) {
// represents the current component key // represents the current component key
......
...@@ -2,7 +2,7 @@ import React from 'react' ...@@ -2,7 +2,7 @@ import React from 'react'
import ReactDOM from 'react-dom' import ReactDOM from 'react-dom'
import HeadManager from './head-manager' import HeadManager from './head-manager'
import { createRouter } from 'next/router' import { createRouter } from 'next/router'
import EventEmitter from 'next-server/dist/lib/event-emitter' import mitt from 'next-server/dist/lib/mitt'
import {loadGetInitialProps, getURL} from 'next-server/dist/lib/utils' import {loadGetInitialProps, getURL} from 'next-server/dist/lib/utils'
import PageLoader from './page-loader' import PageLoader from './page-loader'
import * as envConfig from 'next-server/config' import * as envConfig from 'next-server/config'
...@@ -63,7 +63,7 @@ export let ErrorComponent ...@@ -63,7 +63,7 @@ export let ErrorComponent
let Component let Component
let App let App
export const emitter = new EventEmitter() export const emitter = mitt()
export default async ({ export default async ({
webpackHMR: passedWebpackHMR webpackHMR: passedWebpackHMR
......
/* global document */ /* global document */
import EventEmitter from 'next-server/dist/lib/event-emitter' import mitt from 'next-server/dist/lib/mitt'
// smaller version of https://gist.github.com/igrigorik/a02f2359f3bc50ca7a9c // smaller version of https://gist.github.com/igrigorik/a02f2359f3bc50ca7a9c
function supportsPreload (list) { function supportsPreload (list) {
...@@ -22,7 +22,7 @@ export default class PageLoader { ...@@ -22,7 +22,7 @@ export default class PageLoader {
this.pageCache = {} this.pageCache = {}
this.prefetchCache = new Set() this.prefetchCache = new Set()
this.pageRegisterEvents = new EventEmitter() this.pageRegisterEvents = mitt()
this.loadingRoutes = {} this.loadingRoutes = {}
} }
......
/* eslint-env jest */ /* eslint-env jest */
import EventEmitter from 'next-server/dist/lib/event-emitter' import mitt from 'next-server/dist/lib/mitt'
describe('EventEmitter', () => { describe('EventEmitter', () => {
describe('With listeners', () => { describe('With listeners', () => {
it('should listen to a event', (done) => { it('should listen to a event', (done) => {
const ev = new EventEmitter() const ev = mitt()
ev.on('sample', done) ev.on('sample', done)
ev.emit('sample') ev.emit('sample')
}) })
it('should listen to multiple listeners', () => { it('should listen to multiple listeners', () => {
const ev = new EventEmitter() const ev = mitt()
let cnt = 0 let cnt = 0
ev.on('sample', () => { cnt += 1 }) ev.on('sample', () => { cnt += 1 })
...@@ -22,7 +22,7 @@ describe('EventEmitter', () => { ...@@ -22,7 +22,7 @@ describe('EventEmitter', () => {
}) })
it('should listen to multiple events', () => { it('should listen to multiple events', () => {
const ev = new EventEmitter() const ev = mitt()
const data = [] const data = []
const cb = (name) => { data.push(name) } const cb = (name) => { data.push(name) }
...@@ -36,7 +36,7 @@ describe('EventEmitter', () => { ...@@ -36,7 +36,7 @@ describe('EventEmitter', () => {
}) })
it('should support multiple arguments', () => { it('should support multiple arguments', () => {
const ev = new EventEmitter() const ev = mitt()
let data let data
ev.on('sample', (...args) => { data = args }) ev.on('sample', (...args) => { data = args })
...@@ -46,7 +46,7 @@ describe('EventEmitter', () => { ...@@ -46,7 +46,7 @@ describe('EventEmitter', () => {
}) })
it('should possible to stop listening an event', () => { it('should possible to stop listening an event', () => {
const ev = new EventEmitter() const ev = mitt()
let cnt = 0 let cnt = 0
const cb = () => { cnt += 1 } const cb = () => { cnt += 1 }
...@@ -60,46 +60,11 @@ describe('EventEmitter', () => { ...@@ -60,46 +60,11 @@ describe('EventEmitter', () => {
ev.emit('sample') ev.emit('sample')
expect(cnt).toBe(1) expect(cnt).toBe(1)
}) })
it('should throw when try to add the same listener multiple times', () => {
const ev = new EventEmitter()
const cb = () => {}
ev.on('sample', cb)
const run = () => ev.on('sample', cb)
expect(run).toThrow(/Listener already exists for router event: `sample`/)
})
it('should support chaining like the nodejs EventEmitter', () => {
const emitter = new EventEmitter()
let calledA = false
let calledB = false
emitter
.on('a', () => { calledA = true })
.on('b', () => { calledB = true })
emitter.emit('a')
emitter.emit('b')
expect(calledA).toEqual(true)
expect(calledB).toEqual(true)
})
it('should return an indication on emit if there were listeners', () => {
const emitter = new EventEmitter()
emitter.on('a', () => { })
expect(emitter.emit('a')).toEqual(true)
expect(emitter.emit('b')).toEqual(false)
})
}) })
describe('Without a listener', () => { describe('Without a listener', () => {
it('should not fail to emit', () => { it('should not fail to emit', () => {
const ev = new EventEmitter() const ev = mitt()
ev.emit('aaaa', 10, 20) ev.emit('aaaa', 10, 20)
}) })
}) })
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册