How to access method from other class method that is used as a callback?

python call class method from another class method
python call class method from another method
c++ pointer to member function inside class
python call class method from another file
python call class method from instance
python call class method within class
cannot create a non-constant pointer to member function
c++ call member function pointer

I have the following Javascript class:

class App {

    log_text(text) {
        console.log(text)
    }

    process_response(response) {
        this.log_text(response) // Uncaught TypeError: this.log_text is not a function
        // self.log_text(response) // Uncaught TypeError: self.log_text is not a function
    }

    do_stuff() {
        this.log_text('hello') // OK
    }

    fetch_data() {
        jQuery.get('http://example.com/data/sample.txt', this.process_response, 'text')
    }
}

When calling the method do_stuff, I can access log_text fine by calling this.log_text. However, the method process_response, which is used as a callback handler for jQuery.get as in this example, fails because this represents a totally different object in that context.

Similarly, self.log_text also throws a TypeError.

What would be a possible (or the correct) way to call log_text from process_response as in this example?

What's happening is that you are passing your process_response function and that is all, as you've seen the context of this changes. One fix is to wrap it using arrow syntax, which will preserve the value of this when jQuery fires the callback.

 fetch_data() {
        jQuery.get('http://example.com/data/sample.txt', (r)=> this.process_response(r), 'text')
    }

Class Methods for Graphics Callbacks, To use an ordinary class method as callback for a graphics object, specify the callback For ordinary methods, use dot notation to pass an instance of the class defining sliderCallback); end function sliderCallback(obj,src,~) minVal = get(src Other MathWorks country sites are not optimized for visits from your location. The class must extend from React. If the request is already complete, the callback is fired immediately. The hello method from Developer class has been overridden. The render() lifecycle method is mandatory to output a React element, because after all you may want to display the fetched data at some point.

You can use Function.bind() to set the context of process_response function

fetch_data() {
  jQuery.get('http://example.com/data/sample.txt', this.process_response.bind(this), 'text')
}

Pointers to Member Functions, C++ FAQ, How do I create and use an array of pointer-to-member-function? Note: if it's a static member function of class Fred , its type is the same as if it How do I pass a pointer-to-member-function to a signal handler, X event callback, system call that Normal C functions can be thought of as having a different calling convention  Another approach, which I like best, calls for writing small "wrapper" functions for the methods you want to pass as callbacks and passing the wrapper functions themselves as the callback. The wrapper functions are static members of the same class as the method you originally wanted to pass as callback.

You can use an arrow function, which has a lexical this -

fetch_data() {
  jQuery.get
    ( 'http://example.com/data/sample.txt'
    , r => this.process_response(r)
    , 'text'
    )
}

Or use Function#bind which binds a context (and optionally some arguments) to a function -

fetch_data() {
  jQuery.get
    ( 'http://example.com/data/sample.txt'
    , this.process_response.bind(this)
    , 'text'
    )
}

Or as was done historically, preserve context with a var; this is now less preferred to the above techniques -

fetch_data() {
  var ctx = this
  jQuery.get
    ( 'http://example.com/data/sample.txt'
    , function (r) { ctx.process_response(r) }
    , 'text'
    )
}

New JS features will improve your quality of life, however. Consider coercing your jqXHR to a Promise so you can use async and await -

const get = (opts = {}) =>
  new Promise
    ( (resolve, reject) =>
        $.get(opts)
         .done((req, status, res) => resolve(res))
         .fail((req, status, err) => reject(err))
    )

The result is flatter code and many extraneous functions like fetch_data and process_response are no longer necessary. Even better, our minds are freed from thinking about binding functions and dynamic contexts -

class App {

    log_text(text) {
        console.log(text)
    }

    async main () {
      const res = await
        get ({ url: '/data/sample.txt', dataType: 'text' })

      this.log_text(res)
    }

}

You could even set default options for your get wrapper -

const defaultOpts =
  { dataType: 'text' }

const get = (opts = {}) =>
  new Promise
    ( (resolve, reject) =>
        $.get({ ...defaultOpts, ...opts })
         .done((req, status, res) => resolve(res))
         .fail((req, status, err) => reject(err))
    )

Then using it -

async main () {
  const res = await
    get ({ url: '/data/sample.txt' })

  this.log_text(res)
  // ...
}

Callbacks / Callables, This documentation used callback type information for the same purpose. Accessing protected and private methods from within a class is allowed. Static class  Callback in C/C++ : The mechanism of calling a function from another function is called “callback”. Memory address of a function is represented as ‘function pointer’ in the languages like C and C++. So, the callback is achieved by passing the pointer of function1 () to function2 ().

Python Tutorial: class method vs static method - 2020, So, we should use the following form when we call a method through a class name as In other words, when calling a bound method object, Python provides an instance class Callback: def __init__(self, color): self.color = color def​  Override the callback function name in a JSONP request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. jsonpCallback String containing the callback function name for a JSONP request. mimeType String containing a mime type to override the XMLHttpRequest mime type.

Callback (computer programming), In computer programming, a callback, also known as a "call-after" function, is any executable code that is passed as an argument to other code; Callbacks may also be used to control whether a function acts or not: Xlib This method prints the string sent in the callback */ static void CallBackMethod(string str) { Console. A "callback" is a term that refers to a coding design pattern. In this design pattern executable code is passed as an argument to other code and it is expected to call back at some time. This callback can be synchronous or asynchronous. So, in this way large piece of the internal behavior of a method from the outside of a method can be controlled.

Callbacks, What is needed is a way to decouple the calling function from the called class callback which can forward any calls to another C++ class member method or  Define a static class to contain the extension method. The class must be visible to client code. For more information about accessibility rules, see Access Modifiers. Implement the extension method as a static method with at least the same visibility as the containing class. The first parameter of the method specifies the type that the method

Comments
  • Have you tried this.process_response.bind(this) in jQuery.get?
  • either you can bind the process_response function with this in the class constructor or alternatively you can use es6 arrow syntax as well it does the binding job for you.
  • Thanks @Satpal and warl0ck. That is very helpful. Satpal, would you maybe add that as an alternative answer to Bill Hayden's?