Giter Club home page Giter Club logo

js-exercise-event-emitter's Introduction

JS-exercise-event-emitter

Exercício de event emitter em Javascript usando TDD

Esse é um exercício de uma entrevista técnica de emprego para vaga de Engenheiro de Software. Então você pode utilizá-la para treinar seus conhecimentos antes de uma entrevista javascript.

Para fazer o exercício você terá que instalar o Yarn em sua máquina e estar levemente familiarizado com o desenvolvimento de software orientado a testes (TDD).

Baixe a pasta “exercise-event-emitter-master” e tente solucioná-lo antes de ver a resposta. Procure se focar mais em solucionar o problema do que em eficiência.

Lembre-se: Sempre há mais de uma maneira de se chegar na resposta correta. E o mais importante se divirta!

Event Emitter

The goal of this exercise is to create an event emitter which can listen, unlisten and emit events.

The main module exports an object with a create method which act as a factory and should return a new event emitter every time it is called. The implementation of the emitter itself is up to you.

Running tests

By executing the package.json test script, a jest process will start and re-run the test suite after every file change you made.


Example

import Emitter from './emitter.js'

const emitter = Emitter.create()

const handleMyEvent = () => {
  console.log('Hello!')
}

// Registers the callback `handleMyEvent` to be called when we call emitter.emit passing `myEvent` as parameter
emitter.on('myEvent', handleMyEvent)

// This will call the `handleMyEvent` function
emitter.emit('myEvent')

// Will print "Hello!"

// Unregisters the callback `handleMyEvent`
emitter.off('myEvent', handleMyEvent)

// No function will be called since `myEvent` does not have any callbacks assigned to it anymore
emitter.emit('myEvent')

Documentation

Creating a new Emitter

const EventEmitter = require('...')

// Return a new event emitter
const emitter = EventEmitter.create()

Methods

on

on(event: string, callback: function): function

Registers a callback that runs when event is emitted.

Example:

emitter.on('click', () => {
  console.log('Click!')
})
// register a new listener for the 'click' event

It returns a method which unregisters the listener:

Example:

const cancel = emitter.on('click', () => {
  console.log('Click!')
})

cancel()
// unregister the click listener

off

off(event: string, callback: function)

Unregisters a callback from the event callback list.

Example:

const callback = () => {
  console.log('Click!')
}

// register the listener
emitter.on('click', callback)

// unregister the listener
emitter.off('click', callback)

emit

emit(event: string, data: object)

Execute all callbacks registered for event passing data as a parameter.

Example:

emitter.on('click', () => console.log('Click 1'))
emitter.on('click', () => console.log('Click 2'))
emitter.on('click', () => console.log('Click 3'))

emitter.emit('click')
// Prints:
// Click 1
// Click 2
// Click 3

Every listener callback receives a data object which contains the type of the event and any other property passed on .emit():

Example:

emitter.on('loaded', e => console.log(e))

emitter.emit('loaded', { foo: 'potato' })
// Prints:
// { type: 'loaded', foo: 'potato' }

once

once(event: string, callback: function): function

Registers a callback tha runs only once when event is emitted.

Example:

emitter.once('click', () => console.log('Single click!'))

emitter.emit('click')
emitter.emit('click')

// Prints 'Single click!' only once

race

race(Array<[event: string, callback: function]>): function

Receives a list of [event, callback] and when any of the passed events is emitted, it unregisters all of them.

Example:

emitter.race([
  ['success', () => console.log('Success!')],
  ['failure', () => console.log('Failure :(')],
])

emitter.emit('success') // Prints 'Success!', `success` and `failure` are unregistered.
emitter.emit('failure') // nothing happens

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.