【问题标题】:Store node-addon event natively for later callback本地存储节点插件事件以供以后回调
【发布时间】:2021-04-20 07:27:33
【问题描述】:

我在 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
}

【问题讨论】:

    标签: node.js node-addon-api


    【解决方案1】:

    你可以创建一个持久化的函数引用,像这样:

    ref = Napi::Persistent(emit);
    

    其中 ref 是在函数外部声明的 Napi::FunctionReference 类型。 这将防止在函数返回并超出范围时对其进行垃圾回收。

    查看here了解详情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-18
      • 1970-01-01
      • 1970-01-01
      • 2016-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多