Skip to content

Commit

Permalink
Replace event-emitter.js by mitt (#5987)
Browse files Browse the repository at this point in the history
This PR aims at replacing next-server/lib/event-emitter.js by mitt.

Fix #4908

event-emitter.js is ~400 bytes gzipped vs mitt is 200 bytes
  • Loading branch information
lucleray authored and timneutkens committed Jan 4, 2019
1 parent f40ed30 commit fc19b23
Show file tree
Hide file tree
Showing 6 changed files with 51 additions and 80 deletions.
32 changes: 0 additions & 32 deletions packages/next-server/lib/event-emitter.js

This file was deleted.

38 changes: 38 additions & 0 deletions packages/next-server/lib/mitt.ts
Original file line number Diff line number Diff line change
@@ -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) })
},
}
}
4 changes: 2 additions & 2 deletions packages/next-server/lib/router/router.js
Original file line number Diff line number Diff line change
@@ -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
Expand Down
4 changes: 2 additions & 2 deletions packages/next/client/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions packages/next/client/page-loader.js
Original file line number Diff line number Diff line change
@@ -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) {
Expand All @@ -22,7 +22,7 @@ export default class PageLoader {

this.pageCache = {}
this.prefetchCache = new Set()
this.pageRegisterEvents = new EventEmitter()
this.pageRegisterEvents = mitt()
this.loadingRoutes = {}
}

Expand Down
49 changes: 7 additions & 42 deletions test/unit/EventEmitter.test.js
Original file line number Diff line number Diff line change
@@ -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 })
Expand All @@ -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) }

Expand All @@ -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 })
Expand All @@ -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 }

Expand All @@ -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)
})
})
Expand Down

0 comments on commit fc19b23

Please sign in to comment.