问题描述
我在 javascript 中创建了两个事件,我可以通过 node-addon-api 成功调用它们。但我只能在调用插件函数后立即使用它们。有没有办法保存函数指针以备后用?
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
}
解决方法
你可以创建一个持久化的函数引用,像这样:
ref = Napi::Persistent(emit);
其中 ref 是在函数外部声明的 Napi::FunctionReference 类型。 这将防止它在函数返回并超出范围时被垃圾收集。
有关详细信息,请查看 here。