简体   繁体   中英

Store newly appended elements server-side via socket.io

 // Client function elemToString(elem){ return elem.outerHTML } let child = document.createElement("div") child.textContent = "foo" child.className = "messages" parent.appendChild(child) socket.emit('chatMsg', elemToString(child)) //Server const messages = [] socket.on('chatMsg', elem => { messages.push(elem) })

I have a button that creates a div with content, how can i display newly appended divs to everyone and not just the individual client.

The child variable is an object. When the same is written on network, it will become something like [object object] .

All you need to do is to convert the DOMElement as string & send it via socket. Similarly, when the same is received, it is received as string . You will need to convert the string back in to DOMElement in order to append it into the document.

Refer here to know how to convert a DOMElement to string.

Refer here to know how to convert a string to DOMElement .

Basically, your code will need to changed like this:

// Client
    let child = document.createElement("div")
    child.textContent = `foo`
    child.className = "messages"
    parent.appendChild(child)

    socket.emit('newDiv', domElementToString(child))

function domElementToString(element) {...}

// Server
    socket.on('newDiv' elem => {
      // show newly appended divs
    })


Update:


// if "messages" are array of DOM elements, then the following will work

function stringToDOMElement(string) {...refer the 2nd reference link...}

socket.on('chatMsg', (elem) => {
  messages.push(stringToDOMElement(elem))
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM