mercredi 25 octobre 2017

How to manage state?

  class Book {
    constructor () {
      this.state = { 'isInitializing': true, 'isFlipping': false, 'isZooming': false, 'isPeeled': false, 'isZoomed': false, 'isFlippable': false }
      this.mode = _viewer.getMatch('(orientation: landscape)') ? 'landscape' : 'portrait'
      this.plotter = { 'origin': JSON.parse(`{ "x": "${parseInt(d.getElementsByTagName('body')[0].getBoundingClientRect().width) / 2}", "y": "${parseInt(d.getElementsByTagName('body')[0].getBoundingClientRect().height) / 2}" }`) }
    }
  ...

I have a Book class with many states. The book uses CSS3 animations to turn over pages or pinch to zoom etc., during which its state changes from isFlipping: false to isFlipping: true, isZoomed: false to isZoomed: true.

There are mutually exclusive situations, for example when isZoomed: true the isFlippable must be false.

And then with event listeners:

  const delegateElement = d.getElementById('plotter')

  const handler = (event) => {
    event.stopPropagation()
    event.preventDefault()

    switch (event.type) {
      case 'mouseover':
        _handleMouseOver(event)
        break
      case 'mouseout':
        _handleMouseOut(event)
        break
      case 'mousemove':
        _handleMouseMove(event)
        break
      case 'mousedown':
        _handleMouseDown(event)
        break
      case 'mouseup':
        _handleMouseUp(event)
        break
      case 'click':
        _handleMouseClicks(event)
        break
      case 'dblclick':
        _handleMouseDoubleClick(event)
        break

And then later on depending on state: do stuff.

  const _handleMouseOver = (event) => {
    if (!event.target) return
    // do stuff depending on state, meaning lot of `if else` or `switch` `case ` statements.

  }    
  const _handleMouseOut = (event) => {
    if (!event.target) return
    // do more stuff.
  }

  const _handleMouseMove = (event) => {
    if (!event.target) return
    // do stuff depending on state.
  }
  …
  // more events as per list above… and so on.

Now this is going to make my code very unwieldy and horrible to read. :-(

I wonder what path should I take to organize logic (pattern) and handle state of the book per events as they are fired and animation completed (transitionend etc.).

Aucun commentaire:

Enregistrer un commentaire