node-weak-ref
Version:
Make weak references to JavaScript Objects.
49 lines (46 loc) • 1.3 kB
JavaScript
import { EventEmitter } from 'events';
import b from 'bindings';
const bindings = b("weakref.node");
bindings._setCallback(callback);
const CB = "_CB";
function create(object, callback2) {
const weakref = bindings._create(object, new 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);
}
export { addCallback, callbacks, create, get, isDead, isWeakRef, removeCallback, removeCallbacks };