Error in defining class variable within the constructor not found

Just started delving into CoffeeScript and facing a challenge. In my code snippet below, I initialize WebSocketServer with a number as the first argument and a function as the second argument. However, when the websocket receives a message, @msgHandler suddenly becomes undefined. I attempted to resolve this by assigning @msgHandler to a variable named handler, but that also turned out to be undefined. Any suggestions or ideas on how to tackle this issue would be greatly appreciated. Thank you!

main.coffee

#Utilized for interaction with browser interface
webSocketServ = new sio.WebSocketServer Sauce.Server.WebSocketPort, (data, socketId) ->
    try
        json = JSON.parse(data)
        msgType  = json.msgType
    catch error
        return

    if (this.isAuthed(socketId))
        switch msgType
            when "auth"

            else
                io.websocket 'TODO: ' + cmd        
    else
        if msgType is 'auth'
            token = json.token

socket.coffee

class WebSocketServer
    constructor: (@port, @msgHandler) ->
        @webSockets = []
        @handlers = {}
        @test = []
        @authedSockes = []
        @listen(@port);
        console.log @msgHandler #msgHandler is defined here as [ Function ]

    listen: (port) ->
        @wsServ = engine.listen port
        @wsServ.on 'connection', @onConnect
        io.socket "WebServer socket started on port #{port}"

    onConnect: (client) ->
        io.websocket 'New connection with id of ' + client.id

        handler = @msgHandler #@msgHandler is undefined here?

        client.on 'message', (data) ->
            handler data, client.id
            io.websocket '[' + this.id + '] ' + JSON.stringify(data)

        client.on 'close', ->
            io.websocket '[' + this.id + '] Disconnect'

        client.on 'error', (err) ->
            io.websocket "IO error: " + err

compiled socket.coffee

  WebSocketServer = (function() {
    function WebSocketServer(port, msgHandler) {
      this.port = port;
      this.msgHandler = msgHandler;
      this.webSockets = [];
      this.handlers = {};
      this.test = [];
      this.authedSockes = [];
      this.listen(this.port);
      console.log(this.msgHandler);
    }

    WebSocketServer.prototype.listen = function(port) {
      this.wsServ = engine.listen(port);
      this.wsServ.on('connection', this.onConnect);
      return io.socket("WebServer socket started on port " + port);
    };

    WebSocketServer.prototype.onConnect = function(client) {
      var handler;
      io.websocket('New connection with id of ' + client.id);
      handler = this.msgHandler;
      client.on('message', function(data) {
        handler(data, client.id);
        return io.websocket('[' + this.id + '] ' + JSON.stringify(data));
      });
      client.on('close', function() {
        return io.websocket('[' + this.id + '] Disconnect');
      });
      return client.on('error', function(err) {
        return io.websocket("IO error: " + err);
      });
    };

    WebSocketServer.prototype.isAuthed = function(socketId) {
      return __indexOf.call(this.authedSockets, user) >= 0;
    };

    WebSocketServer.prototype.authSocket = function(socketId) {
      this.authedSockets.push(socketId);
      return io.websocket('Authenticated socket with ID of ' + socketId);
    };

    WebSocketServer.prototype.deauthSocket = function(socketId) {
      return this.authedSockets = this.authedSockets.filter(function(word) {
        return word !== socketId;
      });
    };

    return WebSocketServer;

  })();

Answer №1

There is an issue with accessing an instance property, not just an undefined class variable. This problem stems from the common this context issue in callbacks - where passing a method does not inherently give it knowledge of the instance.

To rectify this in CS, you can utilize the fat arrow syntax for method definitions and other callbacks:

    onConnect: (client) =>
#                       ^^
        io.websocket 'New connection with id of ' + client.id

        handler = @msgHandler # @ is now the expected instance

        client.on 'message', (data) =>
#                                   ^^
            handler data, client.id
            io.websocket '[' + @id + '] ' + JSON.stringify(data)
#                              ^ or did you mean to use `client.` here?

        client.on 'close', () =>
#                          ^^
            io.websocket '[' + @id + '] Disconnect'

        client.on 'error', (err) =>
            io.websocket "IO error: " + err

An alternative (and potentially better) solution could involve letting your WebSocketServer class inherit from the engine's class instead of creating a wrapper around it. Since callbacks are typically invoked on the server instance, direct access to properties would eliminate the need for callback binding.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Rect cannot be resized using mouse events

I am currently working on resizing the rectangle inside the SVG using mouse events. To achieve this, I have created another circle shape at the right bottom edge of the rectangle and implemented resize events on that shape. However, I'm facing an issu ...

Having trouble signing out in Nextjs?

As a newcomer to Reactjs and Nextjs, I am currently working on developing an admin panel. To handle the login functionality, I have implemented the following code in my index.js/login page using session storage: const data = { name: email, password: pa ...

POST request body is not defined

Client Interface: procedure OnButtonClick(Sender: TObject); begin gcm := GetGCMInstance; p := TJavaObjectArray<JString>.Create(1); p.Items[0] := StringToJString('460004329921'); FRegistrationID := JStringToString(gcm.register(p)); ...

What is the best way to display a Base64 image in a server-side DataTable?

This HTML code is designed to load server-side data into a table. The data is retrieved from the controller using AJAX requests. <script type="text/template" id="tablescript"> <td><%=Name%></td> <td><%=PhoneNumber%> ...

Having trouble with uploading an image in Laravel using a modal?

For my laravel inventory system, I am facing an issue with uploading images for products. The old code I used for image upload is not working in my current project where I am utilizing a modal and ajax request to save inputs in the database. Can anyone pro ...

The color scheme detection feature for matching media is malfunctioning on Safari

As I strive to incorporate a Dark Mode feature based on the user's system preferences, I utilize the @media query prefers-color-scheme: dark. While this approach is effective, I also find it necessary to conduct additional checks using JavaScript. de ...

JavaScript - retrieve only the domain from the document.referrer

I am trying to extract only the domain from referrer URLs. Two examples of referrer URLs I encounter frequently are http://www.davidj.com/pages/flyer.asp and http://www.ronniej.com/linkdes.com/?adv=267&loc=897 Whenever I come across URLs like the ones ...

Issue with JQuery closest() selector functionality not working

Currently, I am working on a small coffeescript that will allow me to delete a list from HTML. Included below is a snippet of the sample HTML: <li class="picture col-xs-3" id="picture_38"> <div class="thumbnail"> <img src="/system/upload ...

MUI: Autocomplete received an invalid value. None of the options correspond to the value of `0`

Currently, I am utilizing the MUI autocomplete feature in conjunction with react-hook-form. I have meticulously followed the guidance provided in this insightful response. ControlledAutoComplete.jsx import { Autocomplete, TextField } from "@mui/mater ...

Troubleshooting issues with static serving in Express.js

I'm facing an issue while trying to apply a bootstrap theme to a file created using Jade. The error message indicates that it cannot GET the file. Main JavaScript code snippet: const express = require('express'); const app = express(); ap ...

What is the best way to sort through data retrieved by a server component in a NextJS 13 AppDir?

I've hit a roadblock trying to integrate a search bar that filters server-fetched data in my project using NextJS 13 and AppDir. Despite numerous attempts, I can't seem to get it right. It feels like there's something crucial I'm overlo ...

What is the best way to add a hyperlink to a cell in an Angular Grid column

I need help creating a link for a column cell in my angular grid with a dynamic job id, like /jobs/3/job-maintenance/general. In this case, 3 is the job id. I have element.jobId available. How can I achieve this? Here is the code for the existing column: ...

Encountering CORS issue despite employing a CORS library

Encountering a CORS error while attempting to deploy my project on render using expressjs and react. The project functions smoothly on localhost, but changing the URLs to match the website results in this error: Access to XMLHttpRequest at 'https:// ...

Get the latest html content and save it as a .html file using javascript or jQuery

Looking for a way to save an HTML page as a .html file? Having some trouble with jQuery modifications not being included in the exported file? Check out the code snippet below and let me know if you can spot what's going wrong! I'm still getting ...

Having trouble passing input values from the view to the controller in Angular?

Having an issue with sending data to the controller via my view. Below is a snippet of the code: <form ng-submit="submitMessage()"> <div class="form-group"> <input type="number" class="form-control input ...

Enhance the appearance of the jQuery document.ready function

I'm attempting to customize the jQuery document.ready function <html> <head> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script type="text/javascript> $(function() { c ...

Tips on utilizing Sinon for mocking a function that triggers a REST request

I'm currently navigating my way through sinon and mocha, working on the code and test provided below. My goal is to test the findAll() method without triggering an http request. However, I've encountered an error with the current setup: [TypeErr ...

How can you use jQuery to remove a class from an element after a specified period of time?

After updating a record in the database, I plan to make modifications using an AJAX request. Once that is done, I will dynamically add a class to the rendered div by utilizing the addClass method. The class being added (we'll refer to it as colored) c ...

'jQuery' is not recognized as defined, error no-undef

I am currently working on a file that utilizes jQuery for testing purposes: (function($) { "use strict"; // Start of use strict // Configure tooltips for collapsed side navigation $('.navbar-sidenav [data-toggle="tooltip"]').tooltip({ ...

I am interested in developing a JavaScript program that can calculate multiples of 0.10

I am looking to let users input values that are multiples of 0.10, such as - 0.10, 0.20, 0.30....1.00, 1.10, 1.20...1.90, and so on. When a user enters a value in the text box, I have been checking the following validation: amount % 0.10 == 0 Is this a ...