Store node-addon event natively for later callback

483 views Asked by At

I have two events created in javascript which I can call successfully through node-addon-api. But I only can use them immediately after calling the addon function. Is there any way to save the function pointer for later usage?

const emitter = new EventEmitter()

emitter.on('onCardInserted', () => {
    console.log('card added')
})

emitter.on('onCardRemoved', () => {
    console.log('card removed')
})

addon.Node_CardList_AddCardStatusNotifier(emitter.emit.bind(emitter));
Napi::Boolean Node_CardList_AddCardStatusNotifier(const Napi::CallbackInfo& info){
    Napi::Env env = info.Env();
    Napi::Function emit = info[0].As<Napi::Function>();

    // How to store here the function and env for later usage

    std::make_tuple(&env,&emit) // This isn't working
}
1

There are 1 answers

0
buszkiraly On

You can create a persistent function reference, like this:

ref = Napi::Persistent(emit);

Where ref is of type Napi::FunctionReference declared outside of your function. This will prevent it from being garbage collected when the function returns and it goes out of scope.

Take a look at here for the details.