1

So I'm new to Objected Oriented and Functional Programming in Javascript and I'm not sure I'm following best practices.

Take this code for instance:

class MyClass {
  constructor(a, b) {
    this.a = a
    this.b = b   
  }

  func1() { 
    someService(this.func2, this)   
  }

  func2(val) {  
    this.a = val
  } 
}

function someService(callback, callbackObj) {
    /// Do some work
    callback.call(callbackObj, val) 
}

In order for 'this' to be setup correctly when the callback is invoked, someService needs to not only have a reference to the callback (func2), but also a reference to the object that owns that callback - and it has to be invoked with 'call'.

That means that I have to pass around not only the callback function but also the object that owns it to the service. And so my codebase is now cluttered with 'callback' and 'callbackObj' everywhere - and it's just kind of painful to look at and NOT fun or elegant to work with.

Is there a better/cleaner way of working with callbacks in Javascript?

etayluz
  • 15,920
  • 23
  • 106
  • 151
  • 1
    I guess it better to pass callback as `this.func2.bind(this)`. Service should not know context. You should try to keep it as generic as possible – Rajesh Mar 02 '17 at 05:46
  • 1
    Either you pass a plain function (which can be a bound method), or you pass the whole object and your service knows which method to call. – Bergi Mar 02 '17 at 05:46
  • @Rajesh with your solution there is no need for the 'call' on callback anymore – etayluz Mar 02 '17 at 06:07
  • 1
    Yes. Thats the purpose of using bind. Idea is if you wish to use `.call` you need context but a service should stay independent, so you create a function that has context attached to it and use it. So not service only knows that it will receive a callback and I just have to call it at certain time. – Rajesh Mar 02 '17 at 06:09

0 Answers0