1
\$\begingroup\$

I decided to study EventEmitter and play around with it in React JS for on example of a simple form.
I built EventEmitter and added event 'newdata' to it. On event 'newdata' is called function where the data for form's rendering changes. Then event 'newdata' is emitted with the new data.
I repeated emitting of event using setTimeout to better understand how this works.

I will be happy for the tip on improving the code.

class EventEmitter {
  constructor() {
    this.events = {}
  }

  on(eventName, fn) {
    if(!this.events[eventName]) {
      this.events[eventName] = []
    }

    this.events[eventName].push(fn)
    return () => {
      this.events[eventName] = this.events[eventName].filter(eventFn => fn !== eventFn)
    }
  }

  emit(eventName, data) {
    const event = this.events[eventName]
    if (event) {
      event.forEach(fn => {
        fn.call(null, data)
      })
    }
  }
}

let emitter = new EventEmitter()

class App extends React.Component {
  constructor(props){
    super(props)

    this.state = {
      firstName: '',
      isValid: false,
    }
  }

  handleSubmit(e) {
    e.preventDefault()

    let firstName, isValid

    emitter.on('newdata', function(data) {
      firstName = data['firstName']
      isValid = data['isValid']
    })

    emitter.emit('newdata', {
      firstName: 'Kitty',
      isValid: true,
    })

    this.setState({firstName, isValid})

    if (isValid) {
      console.log('success')
    } else {
      console.log('error')
    }

    setTimeout(() => {

      emitter.emit('newdata', {
        firstName: 'Joni',
        isValid: false,
      })

      this.setState({firstName, isValid})

      if (isValid) {
        console.log('success')
      } else {
        console.log('error')
      }

    }, 1000);
  }

  handleValidation(e) {
    this.setState({
      firstName: e.target.firstName
    })
  }

  render() {
    return (
      <form>
        <label>
          Name:
        </label>
        <input
          type='text'
          name ='firstName'
          value = {this.state.firstName}
          onChange = {this.handleValidation.bind(this)}
        />
        <button onClick = {this.handleSubmit.bind(this)}>
          Submit
        </button>
      </form>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
)
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.