處理訪問模態的使用者

此示例顯示瞭如何以 1-1 為基礎處理與模態互動的使用者。

//client side
function modals(socket) {

    this.sendModalOpen = (modalIdentifier) => {

        socket.emit('openedModal', {
            modal: modalIdentifier
        });
    };

    this.closeModal = () => {
        socket.emit('closedModal', {
            modal: modalIdentifier
        });
    };

}

socket.on('recModalInfo', (data) => {
    for (let x = 0; x < data.info.length; x++) {
        console.log(data.info[x][0] + " has open " + data.info[x][1]);
    }
});

//server side
let modal = new Map();

io.on('connection', (socket) => {

    //Here we are sending any new connections a list of all current modals being viewed with Identifiers.
    //You could send all of the items inside the map() using map.entries

    let currentInfo = [];

    modal.forEach((value, key) => {
        currentInfo.push([key, value]);
    });

    socket.emit('recModalInfo', {
        info: currentInfo
    });

    socket.on('openedModal', (data) => {
        modal.set(socket.id, data.modalIdentifier);
    });

    socket.on('closedModal', (data) => {
        modal.delete(socket.id);
    });

});

通過處理所有模態互動,所有新連線的使用者將獲得有關當前正在檢視哪些使用者的所有資訊,以允許我們根據系統中的當前使用者做出決策。