Pass a typescript class method as a callback

时间:2018-02-26 17:53:55

标签: typescript firebase google-cloud-functions

I'm trying to use Typescript on Firebase Functions, defining a class that has a method I want to pass as a callback to export the function code. I've tried this:

class Foo {
  bar (data) { return data.bar; }
  handler(event) { return this.bar(event.data); }
}

On index.ts I've tried:

functions.pubsub.topic('subscriptions').onPublish(new Foo().handler);

but I get cannot access property 'bar' of undefined, which means this is undefined inside handler.

I then tried to use the call method as:

const fooInstance = new Foo()
functions.pubsub.topic('subscriptions').onPublish((event) => fooInstance.handler.call(fooInstance, event));

But I get the same error. I'm clueless right now. Any suggestions?

1 个答案:

答案 0 :(得分:2)

Here is a version that should work... although I don't know what your onPublish expects, so I have captured the result in a variable for now as I don't know what you want to do with it.

functions.pubsub.topic('subscriptions').onPublish((event) => {
    const result = new Foo().handler(event);
});