What is the best way to access the parent object within an event listener?

Is there a way to access the parent object (not window) within an event listener?

Currently, I am able to get window using self, and the WebSocket object (which is the event listener target) using this. However, what I really want is to retrieve the ScratchCloud object (parent).

Here is the JS code:

var ScratchCloud = function(url, user, project) {
  "use strict";
  this.socket = new WebSocket(url); // Create socket

  this.ws_status = function() {
    var status = this.socket.readyState;
    var message = "Scratch Cloud Data Socket (";
    switch (status) {
      case 0:
        message += "Connecting";
      case 1:
        message += "Open";
      case 2:
        message += "Closing";
      case 3:
        message += "Closed";
    }
    message += ")"
    return message;
  }

  this.ws_log = function(message, func, symbol) {
    if (!func) {
      func = console.log;
    }
    if (symbol) {
      func(this.ws_status(), symbol, message);
    } else {
      func(this.ws_status() + ":", message);
    }
  };

  this.ws_open = function(event) {
    console.log(self === window);
    self.ws_log();
    var handshake = {
      method: "handshake",
      user: user,
      project: project
    };
    handshake = JSON.stringify(handshake) + "\n";
    self.ws_log(handshake, null, ">>");
    event.target.send(handshake);
    self.ws_log();
  }

  this.ws_error = function(event) {
    this.ws_log(console.error, event, ">>");
  };

  this.ws_message = function(event) {
    this.ws_log(console.log, event, ">>");
  };
  this.ws_close = this.ws_message;

  this.socket.onopen = this.ws_open;
  this.socket.onerror = this.ws_error;
  this.socket.onmessage = this.ws_message;
  this.socket.onclose = this.ws_close;
};
new ScratchCloud("wss://clouddata.scratch.mit.edu/", "<user-name>", "<scratch-project>");

Does anyone know how to access the ScratchCloud instance in the ws_open function? I have tried looking into this and self without any luck.

Answer №1

Here, the issue lies with this. Initially, you were introduced to the concept of this in JavaScript. When you tried calling the function with self, it did not work as expected and instead accessed the window object. However, when you used this, you were able to access the WebSocket object. Isn't that correct?

If you wish to utilize this to reference the ScratchCloud function, you need to explicitly bind the this keyword with the ScratchCloud function. To gain a deeper understanding of explicit binding in JavaScript, consider exploring the following resources:

I trust that the above information will be beneficial to you.

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

Are items placed into an array passed by reference or by value?

When working with custom Objects in an Angular context, I define two objects "a" and "b" using an interface. These are created as class attributes along with an empty array of these objects. public a: CustomObj; public b: CustomObj; public array: ...

Find the time interval between two timestamps and output the difference in UNIX timestamp format

Is there a way to determine the time difference between two dateTime values? One date is provided by the user, while the other is the current time: User-submitted time - current time = difference in Unix timestamp The format for the user-submitted time i ...

Issue with Next.js: Callback function not being executed upon form submission

Within my Next.js module, I have a form that is coded in the following manner: <form onSubmit = {() => { async() => await requestCertificate(id) .then(async resp => await resp.json()) .then(data => console.log(data)) .catch(err => console ...

Tips for incorporating JavaScript code into back4app.com using Objective-C:1. Start by accessing the

Currently, I am trying to retrieve "ServerDate" from back4app.com using PFCloud. Unfortunately, I have encountered the following issue: Invalid function: "getServerDate" (Code: 141, Version: 1.13.0) When I attempted to use the code below: [PFCloud ...

What is the best way to access the phone's dialer?

I'm attempting to open the phone dialer in my worklight 6.2 hybrid application by clicking on a button and/or an anchor tag. See the code I've been using below: Button: <button onClick='window.parent.location.href = "tel:+1xxxx"'&g ...

Can Vuejs delay the calculation of a computed property until the component is "ready"?

Within my Vue.js application, I have a `computed` property that relies on a value fetched from an AJAX call. I am looking for a way to delay the calculation of this `computed` property until after the `ready` method has completed. While everything is fun ...

Swapping out characters that are not numerical within a text input field

Is there a way to restrict the input in a text box to only numbers (1-5), a $(dollar) .(decimal) and '(singlequote) during a keyup event? I need a method that will replace any characters typed that are not part of this criteria with a *. Can you pleas ...

What is the best option: using a Javascript template or exploring another

Just starting out in web development. I want to include the same menu on every page of my new website, but I don't want to manually update it in each file whenever there's a change. Is there an easy template engine for JavaScript or another sol ...

How can I retrieve the identifier in Socket.io?

Is there a way to retrieve the unique Id from the server using socket.io? I attempted using clients[socket.id] = socket; However, I encountered an error stating: connections property is deprecated. use getconnections() method Does anyone have any sugg ...

Is there a method to achieve greater accuracy when dividing a large number?

My requirement involves operating on Big Numbers, and I need the results to maintain precision, as demonstrated below: const BN = require('bn.js'); var a = 11060622312717714974 var b = 1570481433500000000000; console.log(a/b); //0.00704282271460 ...

Transforming the Date into Local Time: An Instantaneous Process?

I am currently working with a Kendo UI MVC grid that contains three date columns. These dates, which do not include any time values, are stored in the database as local time rather than UTC. The columns within the grid are defined like so: col ...

Ways to determine if an image has a designated width/height using JavaScript (jQuery)

Similar Question: How can I retrieve the height and width of an image using JavaScript? Typically, we can determine the image width using $('img').width() or $('img').css('width') when a width is specified as shown below ...

How can I set up automatic language selection for Google Translate's menu indexing feature?

My goal is to implement an automatic page translation feature using Google Translate's Library. I have been following the instructions provided in this link: The issue lies in the code snippet below, where the select menu creation works fine, but acc ...

Finding the correct column in a drop-down menu based on a table array using AngularJS

In my controller, I have data like this: $scope.operationData = [ { "label" : "Inventory", "labelType" : "Master Tables", "type" : "PROCESSOR", "outputStreams" : 1, "elementType" : "TABLE", "name" : ...

v-for loop to populate dropdown menu with identical values

Recently, I started working on a points counter app using Vue.js and encountered some issues with the v-for loop and dropdown menu functionality. Within my Vue.js application, I have an array of players as shown below: var app = new Vue({ el: '#l ...

Activating a tab using a JS call in Bootstrap with the data-toggle attribute

My JSP page is using bootstrap's data-toggle="tab" functionality to display tabs. When the page loads, one tab is made active by default. <ul class="nav st-nav-tabs"> <li class="active"><a href="#tab1" data-toggle="tab">First Ta ...

"Using a WMD Editor to show the content of the wmd-preview division and questions on how to save this content in a

I am currently in the process of integrating the WMD editor into my website. Everything seems to be functioning correctly so far, but I have hit a roadblock: How can I store the entered information in my database? I have developed a JS/Ajax function that a ...

The function canvas.toDataURL() is not recognized - error originating from a node-webGL wrapper

I am currently working on converting client-side volume rendering code in the browser to server-side rendering using pure JavaScript. On the server side, I am utilizing node-webgl. My objective is to send the server's canvas content to the client so ...

What is the best method for storing an image from a webpage onto the server using JavaScript?

Is there a way to save the image with the id 'canvasaImg' on my webpage to the server using JavaScript, or does it need to be done with PHP? ...

Creating an import map using jspm2 can be done by following these steps

Currently, my goal is to utilize JSPM module loader to import javascript packages from npm instead of CDN and employ an offline package loader. Now, the next step involves incorporating an importmap script in order to successfully import modules like rea ...