Skip to content

Latest commit

 

History

History
38 lines (31 loc) · 821 Bytes

171.create-callback-on-message-channel.md

File metadata and controls

38 lines (31 loc) · 821 Bytes

173. create callback on message channel

Solution 1

Code

// Function executed only once
const callOnce = (fn)=> (...args)=> {
  if (fn)
    fn(...args)
  fn = null
}

const wrap = (port) => {
  const obj = {}
  obj.postMessage = (message, reply)=> {
    port.postMessage({message, reply})
  }
  port.onmessage = ({message, reply})=> {
    if(obj.onmessage)
      obj.onmessage(message, callOnce(reply))
  }
  return obj
}

class BetterChannel {
  constructor() {
    const {port1, port2} = new SomeChannel()
    this.port1 = wrap(port1)
    this.port2 = wrap(port2)
  }
}

Intuition

Create a new object that encapsulates the functionalities of an existing 'SomeChannel.' Pass both messages and replies in the 'postMessage' method. Call the 'onMessage' function with the received message and reply.