0

I was wondering if its possible to list callbacks in a class?

I already tried the answers listed here: Get functions (methods) of a class

But they do not list callbacks.

export default class Foo {
    public myCallback: () => void;
    private readonly bar: any;

    constructor() {
        console.log(Object.getOwnPropertyNames(this).concat(Object.getOwnPropertyNames(Object.getPrototypeOf(this))​));   
        // [ 'bar', 'constructor', 'biz' ]
        // 'myCallback' is not listed.
     }

    public biz() {
    }
}
Community
  • 1
  • 1
Red Riding Hood
  • 1,932
  • 1
  • 17
  • 36
  • what exactly is the desired result? Your object will have a reference to only one callback (which would be the myCallback property).. what do you mean by listing all of them? – toskv Jan 06 '17 at 13:12
  • I mean get the name of the callback. My desired result would be // [ 'bar', 'constructor', 'biz', 'myCallback' ] – Red Riding Hood Jan 06 '17 at 13:26
  • so what you really want is all the names of the properties of that class – toskv Jan 06 '17 at 13:27
  • Yes, but I already tried answers that supposedly lists all properties, but they doesn't list callbacks. I was afraid my question would be immediately closed. – Red Riding Hood Jan 06 '17 at 13:31

1 Answers1

1

That is because of the way the javascript code is generated by the compiler.

Since the myCallback property is never set it optimizes the code and outputs nothing in javascript.

 var Foo = (function() {
   function Foo() {
     // no my callback property is generated since it's never used
    console.log(Object.getOwnPropertyNames(this).concat(Object.getOwnPropertyNames(Object.getPrototypeOf(this))));

   }
   Foo.prototype.biz = function() {};
   return Foo;
 }());

However if at runtime you actually set that property it will be present. Like this.

class Foo {
  public myCallback: () => void;
  private readonly bar: any;

  constructor() {

  }

  public logMethods() {
    var props = [];
    let obj = this;
    do {
      props = props.concat(Object.getOwnPropertyNames(obj));
    } while (obj = Object.getPrototypeOf(obj));

    props.forEach(method => console.log(method));
  }
}


let a = new Foo();
a.myCallback = () => console.log('abc');

a.logMethods();

You can see the working example here.

toskv
  • 30,680
  • 7
  • 72
  • 74
  • Even if it is used it does not show? In my real code, in the constructor I have `socket.on("myCallback", this.myCallback);` Edit: Will try your edit – Red Riding Hood Jan 06 '17 at 13:41
  • it's not about it being used, but rather it being set. in your case this.myCallback would return undefined. Most likely the code would fail. :) – toskv Jan 06 '17 at 13:42
  • Hmm I suspect you are correct, since I set the callback after the constructor elsewhere in the code. I will take another look at what I am doing. Thanks for the tip! – Red Riding Hood Jan 06 '17 at 13:46
  • you can check the link. it has a running example. – toskv Jan 06 '17 at 13:49