UNPKG

node-weak-ref

Version:

Make weak references to JavaScript Objects.

58 lines (54 loc) 1.47 kB
'use strict'; const events = require('events'); const b = require('bindings'); const bindings = b("weakref.node"); bindings._setCallback(callback); const CB = "_CB"; function create(object, callback2) { const weakref = bindings._create(object, new events.EventEmitter()); if ("function" == typeof callback2) { exports.addCallback(weakref, callback2); } return weakref; } const functions = {}; Object.keys(bindings).forEach(function(name) { functions[name] = bindings[name]; }); function addCallback(ref, callback2) { const emitter = bindings._getEmitter(ref); return emitter.on(CB, callback2); } function removeCallback(ref, callback2) { const emitter = bindings._getEmitter(ref); return emitter.removeListener(CB, callback2); } function callbacks(ref) { const emitter = bindings._getEmitter(ref); return emitter.listeners(CB); } function removeCallbacks(ref) { const emitter = bindings._getEmitter(ref); return emitter.removeAllListeners(CB); } function callback(emitter) { emitter.emit(CB); emitter = null; } function get(ref) { return functions.get(ref); } function isDead(ref) { return functions.isDead(ref); } function isWeakRef(obj) { return functions.isWeakRef(obj); } exports.addCallback = addCallback; exports.callbacks = callbacks; exports.create = create; exports.get = get; exports.isDead = isDead; exports.isWeakRef = isWeakRef; exports.removeCallback = removeCallback; exports.removeCallbacks = removeCallbacks;