I'm trying to make a observer pattern in JavaScript (One might exist in the standard library but I want to implement my own).
I need a container of weak references in order to make sure that the listeners do not keep unused functions loaded. I can use a WeakSet
to do this, however a WeakSet
cannot be iterated through, thus I cannot do for (let l in listeners)
and inform my listeners of a change.
What can I do to solve this? In other languages such as Lua, Java, C, etc I have no problems with this.
I'm not using any external libraries.
const makeObservable = function(obj, value)
{
// Must be a container of weak references.
// But a weakset is not sufficient.
const listeners = new Set();
obj.addListener = function(listener)
{
listeners.add(listener);
};
obj.removeListener = function(listener)
{
listeners.remove(listener);
};
obj.setValue = function(newVal)
{
if (value === newVal) return;
const oldVal = value;
value = newVal;
for (let l of listeners)
{
// Notify all listeners of the change.
l(oldVal, newVal);
}
};
obj.getValue = function()
{
return value;
};
return obj;
};
const obs1 = makeObservable({ }, 5);
const obs2 = makeObservable({ }, 10);
(function()
{
const memory = { };
const lis = function(_, newVal)
{
memory.changed = newVal;
};
// Whenever either changes, update memory.
obs1.addListener(lis);
obs2.addListener(lis);
})();
// 'memory' is out of scope, but still has references pointing to it.
// I have no current way of removing the memory leak until obs1 and obs2 fall out of scope.