"Uncaught ReferenceError: room is not defined" when attempting to disconnect from Twilio Video room

Viewed 895

I'm using the Twilio Video Javascript API to stream and record video content from the browser. The application is built in Nodejs/Express and I am loading the Twilio API from a CDN link in the page. So far I can successfully instantiate a room and record the video on the server with the following code:

    function createAndConnectToRoom(roomName) {
        Twilio.Video.connect(Token, { name: roomName }).then(room => {
            console.log(`Successfully joined a Room: ${room}`);
            room.on('participantConnected', participant => {
                console.log(`A remote Participant connected: ${participant}`);
            });
        }, error => {
            console.error(`Unable to connect to Room: ${error.message}`);
        });

        displayLocalVideo();
    }

My problem is I am unable to disconnect from the server. Ideally, I'd like to have a big button that disconnects the user and terminates the room. On the Twilio docs, they advise using the following code (the outer function is my own, the inner code is from Twilio). However, I receive Uncaught ReferenceError: the room is not defined in the Chrome console when I fire this function with an onclick event.

    function disconnectFromRoom() {
        room.on('disconnected', room => {
            // Detach the local media elements
            room.localParticipant.tracks.forEach(publication => {
                const attachedElements = publication.track.detach();
                attachedElements.forEach(element => element.remove());
            });
        });

        // To disconnect from a Room
        room.disconnect();

    }

I also tried to save "room" to a global variable when it's created and then passing that variable into the disconnect function. But even then I cannot call the room.on.

I seem to be misunderstanding something basic in how to use the API to terminate a room.

2 Answers

Looks like you don't have access to the room variable in the disconnectFromRoom function. Try to hold all the room created in some global variable like window.room and then access the room from window in disconnectFromRoom function.

Please look at this example too.

Move your room.on('disconnect) code into your createAndConnectToRoom function. It does not need to be inside your disconnect function!

In your disconnectFromRoom function:

    function disconnectFromRoom() {
       if (rm) {
          rm.disconnect();
       }
    }

Also want to add that

    room.on('disconnected', room => {

has a namespace collision

Related