处理访问模态的用户

此示例显示了如何以 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);
    });

});

通过处理所有模态交互,所有新连接的用户将获得有关当前正在查看哪些用户的所有信息,以允许我们根据系统中的当前用户做出决策。