Home > Software design >  JavaScript/TypeScript: Continue code execution in first class when button in second class is clicked
JavaScript/TypeScript: Continue code execution in first class when button in second class is clicked

Time:09-16

I want to stop code execution in first class until button, which is created in second class, is clicked. How can I achieve this?

class First {
  constructor() {
    const second = new Second()
    console.log('Print this ONLY when button from Second class is clicked')
  }
}

class Second {
  constructor() {
    const button = document.createElement('button')
    button.innerText = 'Button from second class'

    button.addEventListener('click', () => {
      // Some kind of callback?
      console.log('Clicked')
    })

    document.body.appendChild(button)
  }
}

function myFunction() {
  new First()
}
<html>
<button onclick="myFunction()">Click me!</button>
</html>

CodePudding user response:

Your comment about some kind of callback is correct. You tell your Second class, to callback to your First class when its' button is clicked.

Many different ways of implementing this, but here's one example with minimal edits to your example code.

class First {
  constructor() {
    const second = new Second(() => {
      console.log('Print this ONLY when button from Second class is clicked');
    });
  }
}

class Second {
  constructor(cb) {
    this.cb = cb;
    const button = document.createElement('button')
    button.innerText = 'Button from second class'

    button.addEventListener('click', () => {
      // Some kind of callback?
      this.cb();
      console.log('Clicked')
    })

    document.body.appendChild(button)
  }
}

function myFunction() {
  new First()
}
<button onclick="myFunction()">Click Me</button>

CodePudding user response:

Lee provided the answer I looked for. Here is the same solution, but with the callback returning boolean values (might be useful for someone):

class First {
  constructor() {
    const second = new Second((cb) => {
      console.log('Callback: ', cb)
    })
  }
}

class Second {
  constructor(cb) {
    this.cb = cb

    const container = document.createElement('div')
    container.style.width = '100px'
    container.style.height = '60px'

    const btnSubmit = document.createElement('button')
    btnSubmit.innerText = 'Submit'

    const btnClose = document.createElement('button')
    btnClose.innerText = 'Close'

    btnClose.addEventListener('click', () => {
      this.cb(false)
      document.body.removeChild(container)
    })

    btnSubmit.addEventListener('click', () => {
      this.cb(true)
      document.body.removeChild(container)
    })

    container.append(btnSubmit, btnClose)
    document.body.appendChild(container)
  }
}

function myFunction() {
  new First()
}
<button onclick="myFunction()">Click Me</button>

  • Related