1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00

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
This commit is contained in:
Luc 2019-01-05 04:49:21 +08:00 committed by Tim Neutkens
parent f40ed302df
commit fc19b233eb
6 changed files with 51 additions and 80 deletions

View file

@ -1,32 +0,0 @@
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
}
}

View file

@ -0,0 +1,38 @@
/*
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) })
},
}
}

View file

@ -1,12 +1,12 @@
/* global __NEXT_DATA__ */
import { parse, format } from 'url'
import EventEmitter from '../event-emitter'
import mitt from '../mitt'
import shallowEquals from './shallow-equals'
import { loadGetInitialProps, getURL } from '../utils'
export default class Router {
static events = new EventEmitter()
static events = mitt()
constructor (pathname, query, as, { initialProps, pageLoader, App, Component, ErrorComponent, err } = {}) {
// represents the current component key

View file

@ -2,7 +2,7 @@ import React from 'react'
import ReactDOM from 'react-dom'
import HeadManager from './head-manager'
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 PageLoader from './page-loader'
import * as envConfig from 'next-server/config'
@ -63,7 +63,7 @@ export let ErrorComponent
let Component
let App
export const emitter = new EventEmitter()
export const emitter = mitt()
export default async ({
webpackHMR: passedWebpackHMR

View file

@ -1,5 +1,5 @@
/* 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
function supportsPreload (list) {
@ -22,7 +22,7 @@ export default class PageLoader {
this.pageCache = {}
this.prefetchCache = new Set()
this.pageRegisterEvents = new EventEmitter()
this.pageRegisterEvents = mitt()
this.loadingRoutes = {}
}

View file

@ -1,16 +1,16 @@
/* eslint-env jest */
import EventEmitter from 'next-server/dist/lib/event-emitter'
import mitt from 'next-server/dist/lib/mitt'
describe('EventEmitter', () => {
describe('With listeners', () => {
it('should listen to a event', (done) => {
const ev = new EventEmitter()
const ev = mitt()
ev.on('sample', done)
ev.emit('sample')
})
it('should listen to multiple listeners', () => {
const ev = new EventEmitter()
const ev = mitt()
let cnt = 0
ev.on('sample', () => { cnt += 1 })
@ -22,7 +22,7 @@ describe('EventEmitter', () => {
})
it('should listen to multiple events', () => {
const ev = new EventEmitter()
const ev = mitt()
const data = []
const cb = (name) => { data.push(name) }
@ -36,7 +36,7 @@ describe('EventEmitter', () => {
})
it('should support multiple arguments', () => {
const ev = new EventEmitter()
const ev = mitt()
let data
ev.on('sample', (...args) => { data = args })
@ -46,7 +46,7 @@ describe('EventEmitter', () => {
})
it('should possible to stop listening an event', () => {
const ev = new EventEmitter()
const ev = mitt()
let cnt = 0
const cb = () => { cnt += 1 }
@ -60,46 +60,11 @@ describe('EventEmitter', () => {
ev.emit('sample')
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', () => {
it('should not fail to emit', () => {
const ev = new EventEmitter()
const ev = mitt()
ev.emit('aaaa', 10, 20)
})
})