Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

thebigk's avatar
Level 13

Problem with "this" inside Alpine function

I'm creating a webcam recorder for my application using Alpine. I got most of the things working as expected, except that Chrome throws error for the following block of code -

toggleRecordingStatus() {
                    if(this.mediaRecorder.state === "inactive")
                    {
                        this.recordingStatus = "Stop Recording";
                        this.recordedBlobs = [];
                        this.mediaRecorder.start()
						// Following block throws error. Apparantly "this' ain't working right. 
                        this.mediaRecorder.ondataavailable = function(event) {
                            this.recordedBlobs.push(event.data);
                        };
                    }

Error thrown in console -

Uncaught TypeError: Cannot read properties of undefined (reading 'push')
    at mediaRecorder.ondataavailabl

Can someone help me fix this, please?

0 likes
7 replies
axeloz's avatar
axeloz
Best Answer
Level 2

I think you are missing the arrow notation

Function ( (event) => { … });

Or something in this style. Otherwise you loose context.

1 like
thebigk's avatar
Level 13

@axeloz - appreciate your response. I'm a JS newbie. Did you suggest this ->

this.mediaRecorder.ondataavailable = function(event) => {
                            console.log('ok');
                            this.recordedBlobs.push(event.data);
                        };

phpStorm shows error on the => part.

thebigk's avatar
Level 13

Oh wait! This works -

this.mediaRecorder.ondataavailable = (event) => {
                            console.log('ok');
                            this.recordedBlobs.push(event.data);
                        };

What's with this => ?

axeloz's avatar

@thebigk I’m no JS expert either but this makes sure you keep the context and still have access to « this »

axeloz's avatar

Is it solved then? Don’t hesitate to mark as solution. Enjoy

doldersumsp's avatar

@thebigk This is called an arrow function. It does not bind a new this instance to the function where as the function() { } does get a new instance within the block, curly brackets.

Hope this helps ;)

1 like
axeloz's avatar

You forgot a ( and a ) at the end See my previous post

1 like

Please or to participate in this conversation.