Sending a prototype method as a callback in JavaScript: Here's how to do it

I am struggling with a prototype method that needs to be properly invoked by a callback from the Box2D API. The issue I am facing is that the callback can access the function, but it does not refer to the correct instance of the function. I need help with finding the right syntax to ensure that the callback correctly calls the this.prototype class.

Here is the code snippet that calls the Box2D API:

Box2d.prototype.getBodyAtMouse = function() {
   this.mousePVec = new this.b2Vec2(this.mouseX/this.SCALE, this.mouseY/this.SCALE);
   var aabb = new this.b2AABB();
   aabb.lowerBound.Set(this.mouseX/this.SCALE - 0.001, this.mouseY/this.SCALE - 0.001);
   aabb.upperBound.Set(this.mouseX/this.SCALE + 0.001, this.mouseY/this.SCALE + 0.001);
   this.selectedBody = null;
   var _this = this; 
   this.world.QueryAABB(_this.getBodyCB, aabb);
   return this.selectedBody;

}

Next, we have the Box2D API method that is being called:

b2World.prototype.QueryAABB = function (callback, aabb) {
  var __this = this;
  var broadPhase = __this.m_contactManager.m_broadPhase;

  function WorldQueryWrapper(proxy) {
     return callback(broadPhase.GetUserData(proxy));
  };
  broadPhase.Query(WorldQueryWrapper, aabb);

}

Finally, we have the callback function that I need the API to reference correctly:

Box2d.prototype.getBodyCB = function(fixture) 
{
  if(fixture.GetBody().GetType() != this.b2Body.b2_staticBody) {
   if(fixture.GetShape().TestPoint(fixture.GetBody().GetTransform(), this.mousePVec)) {
      selectedBody = fixture.GetBody();
      return false;
   }
}
return true;

}

Answer №1

One option is to:

let self = this;
this.world.QueryAABB(function(fixture){
   self.getFixtureData(fixture);
}, boundingBox);

Alternatively:

this.world.QueryAABB(this.getFixtureData.bind(this), boundingBox);

(this method may not work on older browsers, but can be easily polyfilled)

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

Having trouble getting autocomplete to work with JQuery UI?

Currently facing issues in implementing the Amazon and Wikipedia Autocomplete API. It seems that a different autocomplete service needs to be used based on the search parameter. Unfortunately, neither of the services work when adding "?search=5" for Wikipe ...

Guide to Sending and Scheduling Notifications through HTML 5's Notification Web APIs

Is it possible to utilize Web APIs to Schedule Notifications and send them at specific times? I am working on a CMS application that allows users to schedule and send push notifications for their mobile apps. I am interested in implementing something sim ...

Updating files in a Next.js project and automatically refreshing the page without the need to rerun 'npm run'

For a while now, I've been developing websites using a traditional LAMP stack with javascript (including jQuery) for the frontend. Recently, I decided to explore using javascript for the backend as well and started learning next.js. In the older meth ...

How come I am unable to reinitialize my array using setState?

Within my camera module, I am aiming to store photos in a bucket every time three photos are taken. Utilizing state in react, I save the image blobs in an array. Initially, everything functions flawlessly for the first three snapshots; however, subsequentl ...

Encountering a router issue when trying to export using Express middleware

New to this and encountering a router error when trying to export in Express. How can I resolve this issue for both the router and the mongo model? Hoping for a successful export process in both the router and the mongo model. ...

Learn the process of seamlessly uploading various document formats, videos, and previewing documents with Angular software

I am having trouble viewing uploaded files in the carousel. While I can see video and image files, other document formats are not displaying. Can someone please recommend a solution to enable viewing all types of documents as well? mydata = [] onSelect ...

What is the best way to identify when a page has been refreshed in Reactjs?

Imagine a set of pages with steps: 1, 2, and 3. If a page reloads during the second or third step, it must be directed back to the first step. Is there a way to identify when a page has been reloaded? ...

Customizing Marker Clusters with ui-leaflet: A guide on changing marker cluster colors

I'm trying to customize the markerCluster color in a non-default way. I've been exploring the API and it looks like the recommendation is to modify a divIcon after creation, possibly like this: var markers = L.markerClusterGroup({ iconCreateFunc ...

Display numeric data when hovering over circles in the Google Maps API using Javascript

I recently implemented the Google Maps example code that displays a circle hovering over a city, with the size of the circle representing the population. I'm looking to enhance this feature by including numeric data display on mouseover as well. Any a ...

Changing the names of the remaining variables while object destructuring in TypeScript

UPDATE: I have created an issue regarding this topic on github: https://github.com/Microsoft/TypeScript/issues/21265 It appears that the syntax { ...other: xother } is not valid in JavaScript or TypeScript, and should not compile. Initial Query: C ...

Looking for a list of events in Express.js?

I've been searching through the official documentation, but I couldn't find a list of events for express. Does anyone know if there's something like 'route-matched' so that I can use app.on('route-matched', () => {})? ...

What is the best way to fetch d3 data from a service?

I've been exploring a tutorial on creating charts with d3, which can be found at: When it comes to loading data for use in d3, I typically rely on the following code snippet: d3.tsv("data.tsv", type, function(error, data) { The file "data.tsv" is c ...

Unveil the Expressjs middleware within the API Client

I am currently developing a Nodejs API Client with the following simple form: //client.js function Client (appId, token) { if (!(this instanceof Client)) { return new Client(appId, token); } this._appId = appId; this._token = tok ...

Issue with Yup and Formik not validating checkboxes as expected

I'm struggling to figure out why the validation isn't functioning as expected: export default function Check() { const label = { inputProps: { "aria-label": "termsOfService" } }; const formSchema = yup.object().shape({ ...

Achieving dynamic serving of static files using Rollup and integrating seamlessly with node-resolve

Currently, I am in the process of building a library using TSDX, which is a powerful CLI tool for package development based on Rollup. My project involves a collection of country flags SVGs that need to be imported and displayed dynamically when required. ...

How to ensure an object is consistently rendered above all others using Three.js

Currently working on adding a dynamic command arrow that follows the cursor on the display. However, I have encountered an issue where it gets obscured by other elements on the screen. Is there a method to adjust the z-buffer or implement a workaround to ...

Navigating the reactive array in Vue 3 with finesse

Currently, I'm facing some challenges with my Vue 3 app in terms of getting things to work as expected. The main issue lies in properly accessing a reactive array. Let me provide you with the code for better comprehension: Within my global store sto ...

Problem arising from animation not commencing at expected starting point

Creating a feature on an app that involves breathing exercises using CSS animations. The challenge I'm facing is ensuring the words "exhale" and "inhale" appear synchronously with the animation of a circle shrinking and enlarging. However, the animati ...

Creating dynamic HTML table rows with data from a JSON object

Query: In search of a Jquery or JavaScript solution for generating dynamic table rows with colspan using the JSON structure provided below. I am encountering difficulties in creating the necessary rows and have attempted several approaches without success ...

Exploring Next.js Font Styling and Utilizing CSS Variables

I'm attempting to implement the "next" method for adding fonts, but I find the process described quite complex just to preload a font. I experimented with exporting a function to create the font and then using a variable tag to generate a CSS variabl ...