What is the mechanism behind callback interaction between two different classes?

I'm currently enrolled in a course and I'm delving into the mechanics of callbacks between two classes. To aid my understanding, I have crafted this example:

    function Car() {

        this.offer = {};

        this.OfferUpdate = () => {
            this.callback(this.offer)
        }

        this.callback = function(){};

        this.Listener = (callback) => {
            this.callback = callback;
        }
    }

    var car = new Car();
    car.offer = {
        model: ['A4', 'A5', 'A6'],
        engine: ['TDI', 'TFSI']
    }

    class Car_showroom {

        constructor() {
            this.model = ['A4'];
            this.engine = ['TDI'];

            car.Listener((newItems) => {
                // Callback logic here
                this.model = newItems.model
                this.engine = newItems.engine
            })
        }
    }

let car_showroom = new Car_showroom();

let p = document.createElement("p")
let p2 = document.createElement("p")
let text = document.createTextNode("car.offer: " + JSON.stringify(car.offer));
let text2 = document.createTextNode("car_showroom: " + JSON.stringify(car_showroom))
p.appendChild(text);
document.body.appendChild(p);
p2.appendChild(text2);
document.body.appendChild(p2);

car.OfferUpdate(); // Invoking callback

let p3 = document.createElement("p")
let text3 = document.createTextNode("car_showroom after  car.OfferUpdate(): " + JSON.stringify(car_showroom))
p3.appendChild(text3);
document.body.appendChild(p3);
    

Upon triggering the car.OfferUpdate(), the associated callback within the method is activated, subsequently initiating the listner() method. However, I am puzzled as to how.

How exactly does executing this.callback(this.offer) lead to the invocation of the listner() method?

Answer №1

How come when we use this.callback(this.offer), it ends up triggering the listner() method?

In this code snippet, a function is passed into car.Listener:

car.Listener((newItems) => {
    this.model = newItems.model
    this.engine = newItems.engine
})

Within car.Listener, the following assignment takes place:

this.callback = callback;

This line saves the reference to the function passed as an argument to car.Listener (the arrow function that sets model and

engine</code) in its <code>callback
property. Subsequently, calling this.callback(...) invokes that arrow function, not Listener.

To clarify the distinction between the function provided and the usage of car.Listener, consider rephrasing the initial code block like so:

// Define a callback for `car`
const ourCallback = (newItems) => {
    this.model = newItems.model
    this.engine = newItems.engine
};
// Supply the callback to `car`
car.Listener(ourCallback)

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

Touch Screen Button Interaction

Planning to create a Kiosk website with HTML5 that includes point and drag & drop functionality. The site will have buttons and images for user interaction, with actions triggered by finger touches on the screen instead of mouse clicks. Would it be more ...

Tips for sending User First Name and ID through a Javascript tag on the WordPress Backend

Struggling to integrate Usetiful with my WordPress Backend. I am aiming to label the users and transmit data to Usetiful for enhanced personalization. Even though I successfully retrieved and sent the User ID to Usetiful after researching similar Q/A thr ...

Clicking on an element in Reactjs will result in the value being

I currently have a variable called id with a value assigned to it. My goal is to make this id equal to null when the user clicks on the ClearIcon, so that it doesn't match location.id const [getId, setId] = useState(id) const resetId = () => ...

What are the best ways to get HTML tags functioning properly within Angular.js?

When trying to print a response from a different server that contains a lot of HTML code, how can I display it in a single container? In jQuery, you can achieve this with the following code: $("#xyz").html("<h1>Hello World</h1>& ...

Error Handling with Firebase Cloud Firestore and State Management in Vue using Vuex (firebase.firestore.QuerySnapshot)

Upon examining the code, I noticed an issue with docChanges. It seems to be a function, but when I try to use docChanges().doc.data().userId, I encounter the error message: store.js?3bf3:21 Uncaught TypeError: Cannot read property 'doc' of undefi ...

Most effective method for storing and retrieving data on the client side

In my ASP web application, I am facing a challenge with listboxes as changes in item selection happen frequently and quickly. This results in slow performance when trying to retrieve the necessary information through postbacks. So, I am trying to figure o ...

The `arrangeComplete` event in jQuery Isotope is failing to trigger

Here is my jQuery code utilizing the Isotope plugin: $(document).ready(function() { /** * Set up Isotope */ var $grid = $('.grid').isotope({ "itemSelector": ".grid-item", layoutMode: 'masonry', ...

Challenges with using multiple setInterval() functions for handling AJAX calls - (implementing a cooldown system for items stored in

I've encountered an issue with my code and need some help to resolve it. The expected behavior is that when _loadInventory() is called, it should then apply _loadCooldowns() to all elements with the .cooldown class, which essentially function as count ...

Bidirectional Data Binding Using Meteor and React

When using Meteor, the getMeteorData() method is preferred over getInitialState(). But how can we achieve binding, especially with regards to a user's surname in their profile? ... getMeteorData() { return { u = Meteor.user() } }, componentRen ...

Incorporating a YouTube or Vimeo video while maintaining the proper aspect ratio

On my video page, I embed Vimeo videos dynamically with only the video ID. This causes issues with the aspect ratio as black bars appear on the sides due to the lack of width and height settings. The dynamic video ID is implemented like this: <iframe ...

Explain the contrast between specifying a function name in the onclick react event versus invoking it using a callback

Can someone explain the distinction between these two React statements? <Button onClick={this.Callme}></Button> <Button onClick={()=>this.Callme()}></Button> Is it merely a syntax difference or is there an impact on functional ...

Having trouble with jest mocking a function - it's not functioning as expected

I decided to create a simple test using jest to simulate a date change function. Here is the code snippet: import React from 'react'; import '@testing-library/jest-dom'; import { render, screen } from '@testing-library/react' ...

Switched from btao to Buffer, however encountering a TypeError while trying to push to Vercel

I am currently working on an application in Next.js where I need to encode my image to base64. Initially, I used btao and it worked well until I tried deploying to Vercel, which resulted in an error stating that btao was undefined. After researching a solu ...

What is the best way to utilize a portion of the data retrieved from an API call as the output for a function?

After extensive research and testing, I have been exploring ways to make API calls in node js. Currently, my focus is on utilizing a portion of the JSON object returned from an API call within a module to generate a Token. var request = require("request") ...

The timing of the RequestAnimationFrame function varies based on the dimensions of my canvas

In my application, I have a canvas that dynamically adjusts its CSS size based on the window size. The main gameplay loop in my code looks like this: run = function(){ console.log(timerDiff(frameTime)); game.inputManage(); game.logics(); ...

Execute the function if the text or value begins with a certain character

I'm trying to determine whether the text within a span starts with the letter "x" and then execute a function. I've come across using "^" in strings for this purpose, but am having trouble implementing it to check the text... <span>xfoo&l ...

"Utilizing Google Tag Manager to trigger events and push them to the data layer

My goal with this code is to trigger an event in the data layer through Google Tag Manager whenever a user hovers over a specific area on the website for at least 1 second. The challenge I'm facing is that I have 8 other areas on the site using the sa ...

Can someone guide me on implementing Node.js clusters in my basic Express application?

— I have successfully developed a basic application that retrieves data (50 items) from a Redis DB and displays it on localhost. After running an ApacheBench test with parameters c = 100, n = 50000, I am achieving around 150 requests/sec on my aging dual ...

What is the relationship between JavaScript and the height of a window?

Consider the code snippet below: 24 <script type="text/javascript"> 25 26 function UpdateDisplay($isVisible){ 27 if($isVisible) 28 $('.relatedContent').stop().css({ 29 "transform": "tr ...

A guide to resizing images for uploading in Node.js using Jimp without the need for refreshing the page

My goal is to resize a file server-side using Jimp before uploading it to Cloudinary in a node.js environment. Here's the controller I'm using: exports.uploadImage = async (req, res) => { if (!req.files) { return res.status(400).json({ m ...