Are lapsed listeners preventable in javascript? - javascript

My question is really "Is the lapsed listener problem preventable in javascript?" but apparently the word "problem" causes a problem.
The wikipedia page says the lapsed listener problem can be solved by the subject holding weak references to the observers. I've implemented that before in Java and it works nicely, and I thought I'd implement it in Javascript, but now I don't see how. Does javascript even have weak references? I see there are WeakSet and WeakMap which have "Weak" in their names, but they don't seem to be helpful for this, as far as I can see.
Here's a jsfiddle showing a typical case of the problem.
The html:
<div id="theCurrentValueDiv">current value: false</div>
<button id="thePlusButton">+</button>
The javascript:
'use strict';
console.log("starting");
let createListenableValue = function(initialValue) {
let value = initialValue;
let listeners = [];
return {
// Get the current value.
get: function() {
return value;
},
// Set the value to newValue, and call listener()
// for each listener that has been added using addListener().
set: function(newValue) {
value = newValue;
for (let listener of listeners) {
listener();
}
},
// Add a listener that set(newValue) will call with no args
// after setting value to newValue.
addListener: function(listener) {
listeners.push(listener);
console.log("and now there "+(listeners.length==1?"is":"are")+" "+listeners.length+" listener"+(listeners.length===1?"":"s"));
},
};
}; // createListenable
let theListenableValue = createListenableValue(false);
theListenableValue.addListener(function() {
console.log(" label got value change to "+theListenableValue.get());
document.getElementById("theCurrentValueDiv").innerHTML = "current value: "+theListenableValue.get();
});
let nextControllerId = 0;
let thePlusButton = document.getElementById("thePlusButton");
thePlusButton.addEventListener('click', function() {
let thisControllerId = nextControllerId++;
let anotherDiv = document.createElement('div');
anotherDiv.innerHTML = '<button>x</button><input type="checkbox"> controller '+thisControllerId;
let [xButton, valueCheckbox] = anotherDiv.children;
valueCheckbox.checked = theListenableValue.get();
valueCheckbox.addEventListener('change', function() {
theListenableValue.set(valueCheckbox.checked);
});
theListenableValue.addListener(function() {
console.log(" controller "+thisControllerId+" got value change to "+theListenableValue.get());
valueCheckbox.checked = theListenableValue.get();
});
xButton.addEventListener('click', function() {
anotherDiv.parentNode.removeChild(anotherDiv);
// Oh no! Our listener on theListenableValue has now lapsed;
// it will keep getting called and updating the checkbox that is no longer
// in the DOM, and it will keep the checkbox object from ever being GCed.
});
document.body.insertBefore(anotherDiv, thePlusButton);
});
In this fiddle, the observable state is a boolean value, and you can add and remove checkboxes that view and control it, all kept in sync by listeners on it.
The problem is that when you remove one of the controllers, its listener doesn't go away: the listener keeps getting called and updating the controller checkbox and prevents the checkbox from being GCed, even though the checkbox is no longer in the DOM and is otherwise GCable. You can see this happening in the javascript console since the listener callback prints a message to the console.
What I'd like instead is for the controller DOM node and its associated value listener to become GCable when I remove the node from the DOM. Conceptually, the DOM node should own the listener, and the observable should hold a weak reference to the listener. Is there a clean way to accomplish that?
I know I can fix the problem in my fiddle by making the x button explicitly remove the listener along with the DOM subtree, but that doesn't help in the case that some other code in the app later removes part of the DOM containing my controller node, e.g. by executing document.body.innerHTML = ''. I'd like set things up so that, when that happens, all the DOM nodes and listeners I created get released and become GCable. Is there a way?

Custom_elements offer a solution to the lapsed listener problem. They are supported in Chrome and Safari and (as of Aug 2018), are soon to be supported on Firefox and Edge.
I did a jsfiddle with HTML:
<div id="theCurrentValue">current value: false</div>
<button id="thePlusButton">+</button>
And a slightly modified listenableValue, which now has the ability to remove a listener:
"use strict";
function createListenableValue(initialValue) {
let value = initialValue;
const listeners = [];
return {
get() { // Get the current value.
return value;
},
set(newValue) { // Set the value to newValue, and call all listeners.
value = newValue;
for (const listener of listeners) {
listener();
}
},
addListener(listener) { // Add a listener function to call on set()
listeners.push(listener);
console.log("add: listener count now: " + listeners.length);
return () => { // Function to undo the addListener
const index = listeners.indexOf(listener);
if (index !== -1) {
listeners.splice(index, 1);
}
console.log("remove: listener count now: " + listeners.length);
};
}
};
};
const listenableValue = createListenableValue(false);
listenableValue.addListener(() => {
console.log("label got value change to " + listenableValue.get());
document.getElementById("theCurrentValue").innerHTML
= "current value: " + listenableValue.get();
});
let nextControllerId = 0;
We can now define a custom HTML element <my-control>:
customElements.define("my-control", class extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
const n = nextControllerId++;
console.log("Custom element " + n + " added to page.");
this.innerHTML =
"<button>x</button><input type=\"checkbox\"> controller "
+ n;
this.style.display = "block";
const [xButton, valueCheckbox] = this.children;
xButton.addEventListener("click", () => {
this.parentNode.removeChild(this);
});
valueCheckbox.checked = listenableValue.get();
valueCheckbox.addEventListener("change", () => {
listenableValue.set(valueCheckbox.checked);
});
this._removeListener = listenableValue.addListener(() => {
console.log("controller " + n + " got value change to "
+ listenableValue.get());
valueCheckbox.checked = listenableValue.get();
});
}
disconnectedCallback() {
console.log("Custom element removed from page.");
this._removeListener();
}
});
The key point here is that disconnectedCallback() is guaranteed to be called when the <my-control> is removed from the DOM whatever reason. We use it to remove the listener.
You can now add the first <my-control> with:
const plusButton = document.getElementById("thePlusButton");
plusButton.addEventListener("click", () => {
const myControl = document.createElement("my-control");
document.body.insertBefore(myControl, plusButton);
});
(This answer occurred to me while I was watching this video, where the speaker explains other reasons why custom elements could be useful.)

You can use mutation observers which
provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature which was part of the DOM3 Events specification.
An example of how this can be used can be found in the code for on-load
if (window && window.MutationObserver) {
var observer = new MutationObserver(function (mutations) {
if (Object.keys(watch).length < 1) return
for (var i = 0; i < mutations.length; i++) {
if (mutations[i].attributeName === KEY_ATTR) {
eachAttr(mutations[i], turnon, turnoff)
continue
}
eachMutation(mutations[i].removedNodes, function (index, el) {
if (!document.documentElement.contains(el)) turnoff(index, el)
})
eachMutation(mutations[i].addedNodes, function (index, el) {
if (document.documentElement.contains(el)) turnon(index, el)
})
}
})
observer.observe(document.documentElement, {
childList: true,
subtree: true,
attributes: true,
attributeOldValue: true,
attributeFilter: [KEY_ATTR]
})
}

Related

How to write code to check if the value of a variable has changed in real time (JavaScript) [duplicate]

Is it possible to have an event in JS that fires when the value of a certain variable changes? JQuery is accepted.
This question was originally posted in 2009 and most of the existing answers are either outdated, ineffective, or require the inclusion of large bloated libraries:
Object.watch and Object.observe are both deprecated and should not be used.
onPropertyChange is a DOM element event handler that only works in some versions of IE.
Object.defineProperty allows you to make an object property immutable, which would allow you to detect attempted changes, but it would also block any changes.
Defining setters and getters works, but it requires a lot of setup code and it does not work well when you need to delete or create new properties.
As of 2018, you can now use the Proxy object to monitor (and intercept) changes made to an object. It is purpose built for what the OP is trying to do. Here's a basic example:
var targetObj = {};
var targetProxy = new Proxy(targetObj, {
set: function (target, key, value) {
console.log(`${key} set to ${value}`);
target[key] = value;
return true;
}
});
targetProxy.hello_world = "test"; // console: 'hello_world set to test'
The only drawbacks of the Proxy object are:
The Proxy object is not available in older browsers (such as IE11) and the polyfill cannot fully replicate Proxy functionality.
Proxy objects do not always behave as expected with special objects (e.g., Date) -- the Proxy object is best paired with plain Objects or Arrays.
If you need to observe changes made to a nested object, then you need to use a specialized library such as Observable Slim (which I have published). It works like this:
var test = {testing:{}};
var p = ObservableSlim.create(test, true, function(changes) {
console.log(JSON.stringify(changes));
});
p.testing.blah = 42; // console: [{"type":"add","target":{"blah":42},"property":"blah","newValue":42,"currentPath":"testing.blah",jsonPointer:"/testing/blah","proxy":{"blah":42}}]
Yes, this is now completely possible!
I know this is an old thread but now this effect is possible using accessors (getters and setters): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters
You can define an object like this, in which aInternal represents the field a:
x = {
aInternal: 10,
aListener: function(val) {},
set a(val) {
this.aInternal = val;
this.aListener(val);
},
get a() {
return this.aInternal;
},
registerListener: function(listener) {
this.aListener = listener;
}
}
Then you can register a listener using the following:
x.registerListener(function(val) {
alert("Someone changed the value of x.a to " + val);
});
So whenever anything changes the value of x.a, the listener function will be fired. Running the following line will bring the alert popup:
x.a = 42;
See an example here: https://jsfiddle.net/5o1wf1bn/1/
You can also user an array of listeners instead of a single listener slot, but I wanted to give you the simplest possible example.
Using Prototype: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
// Console
function print(t) {
var c = document.getElementById('console');
c.innerHTML = c.innerHTML + '<br />' + t;
}
// Demo
var myVar = 123;
Object.defineProperty(this, 'varWatch', {
get: function () { return myVar; },
set: function (v) {
myVar = v;
print('Value changed! New value: ' + v);
}
});
print(varWatch);
varWatch = 456;
print(varWatch);
<pre id="console">
</pre>
Other example
// Console
function print(t) {
var c = document.getElementById('console');
c.innerHTML = c.innerHTML + '<br />' + t;
}
// Demo
var varw = (function (context) {
/**
* Declare a new variable.
*
* #param {string} Variable name.
* #param {any | undefined} varValue Default/Initial value.
* You can use an object reference for example.
*/
return function (varName, varValue) {
var value = varValue;
Object.defineProperty(context, varName, {
get: function () { return value; },
set: function (v) {
value = v;
print('Value changed! New value: ' + value);
}
});
};
})(window);
varw('varWatch'); // Declare without initial value
print(varWatch);
varWatch = 456;
print(varWatch);
print('---');
varw('otherVarWatch', 123); // Declare with initial value
print(otherVarWatch);
otherVarWatch = 789;
print(otherVarWatch);
<pre id="console">
</pre>
No.
But, if it's really that important, you have 2 options (first is tested, second isn't):
First, use setters and getters, like so:
var myobj = {a : 1};
function create_gets_sets(obj) { // make this a framework/global function
var proxy = {}
for ( var i in obj ) {
if (obj.hasOwnProperty(i)) {
var k = i;
proxy["set_"+i] = function (val) { this[k] = val; };
proxy["get_"+i] = function () { return this[k]; };
}
}
for (var i in proxy) {
if (proxy.hasOwnProperty(i)) {
obj[i] = proxy[i];
}
}
}
create_gets_sets(myobj);
then you can do something like:
function listen_to(obj, prop, handler) {
var current_setter = obj["set_" + prop];
var old_val = obj["get_" + prop]();
obj["set_" + prop] = function(val) { current_setter.apply(obj, [old_val, val]); handler(val));
}
then set the listener like:
listen_to(myobj, "a", function(oldval, newval) {
alert("old : " + oldval + " new : " + newval);
}
Second, you could put a watch on the value:
Given myobj above, with 'a' on it:
function watch(obj, prop, handler) { // make this a framework/global function
var currval = obj[prop];
function callback() {
if (obj[prop] != currval) {
var temp = currval;
currval = obj[prop];
handler(temp, currval);
}
}
return callback;
}
var myhandler = function (oldval, newval) {
//do something
};
var intervalH = setInterval(watch(myobj, "a", myhandler), 100);
myobj.set_a(2);
Sorry to bring up an old thread, but here is a little manual for those who (like me!) don't see how Eli Grey's example works:
var test = new Object();
test.watch("elem", function(prop,oldval,newval){
//Your code
return newval;
});
Hope this can help someone
As Luke Schafer's answer (note: this refers to his original post; but the whole point here remains valid after the edit), I would also suggest a pair of Get/Set methods to access your value.
However I would suggest some modifications (and that's why I'm posting...).
A problem with that code is that the field a of the object myobj is directly accessible, so it's possible to access it / change its value without triggering the listeners:
var myobj = { a : 5, get_a : function() { return this.a;}, set_a : function(val) { this.a = val; }}
/* add listeners ... */
myobj.a = 10; // no listeners called!
Encapsulation
So, to guarantee that the listeners are actually called, we would have to prohibit that direct access to the field a. How to do so? Use a closure!
var myobj = (function() { // Anonymous function to create scope.
var a = 5; // 'a' is local to this function
// and cannot be directly accessed from outside
// this anonymous function's scope
return {
get_a : function() { return a; }, // These functions are closures:
set_a : function(val) { a = val; } // they keep reference to
// something ('a') that was on scope
// where they were defined
};
})();
Now you can use the same method to create and add the listeners as Luke proposed, but you can rest assured that there's no possible way to read from or write to a going unnoticed!
Adding encapsulated fields programmatically
Still on Luke's track, I propose now a simple way to add encapsulated fields and the respective getters/setters to objects by the means of a simple function call.
Note that this will only work properly with value types. For this to work with reference types, some kind of deep copy would have to be implemented (see this one, for instance).
function addProperty(obj, name, initial) {
var field = initial;
obj["get_" + name] = function() { return field; }
obj["set_" + name] = function(val) { field = val; }
}
This works the same as before: we create a local variable on a function, and then we create a closure.
How to use it? Simple:
var myobj = {};
addProperty(myobj, "total", 0);
window.alert(myobj.get_total() == 0);
myobj.set_total(10);
window.alert(myobj.get_total() == 10);
Recently found myself with the same issue. Wanted to listen for on change of a variable and do some stuff when the variable changed.
Someone suggested a simple solution of setting the value using a setter.
Declaring a simple object that keeps the value of my variable here:
var variableObject = {
value: false,
set: function (value) {
this.value = value;
this.getOnChange();
}
}
The object contains a set method via which I can change the value. But it also calls a getOnChange() method in there. Will define it now.
variableObject.getOnChange = function() {
if(this.value) {
// do some stuff
}
}
Now whenever I do variableObject.set(true), the getOnChange method fires, and if the value was set as desired (in my case: true), the if block also executes.
This is the simplest way I found to do this stuff.
If you're using jQuery {UI} (which everyone should be using :-) ), you can use .change() with a hidden <input/> element.
AngularJS (I know this is not JQuery, but that might help. [Pure JS is good in theory only]):
$scope.$watch('data', function(newValue) { ..
where "data" is name of your variable in the scope.
There is a link to doc.
For those tuning in a couple years later:
A solution for most browsers (and IE6+) is available that uses the onpropertychange event and the newer spec defineProperty. The slight catch is that you'll need to make your variable a dom object.
Full details:
http://johndyer.name/native-browser-get-set-properties-in-javascript/
Easiest way I have found, starting from this answer:
// variable holding your data
const state = {
count: null,
update() {
console.log(`this gets called and your value is ${this.pageNumber}`);
},
get pageNumber() {
return this.count;
},
set pageNumber(pageNumber) {
this.count = pageNumber;
// here you call the code you need
this.update(this.count);
}
};
And then:
state.pageNumber = 0;
// watch the console
state.pageNumber = 15;
// watch the console
The functionality you're looking for can be achieved through the use of the "defineProperty()" method--which is only available to modern browsers:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
I've written a jQuery extension that has some similar functionality if you need more cross browser support:
https://github.com/jarederaj/jQueue
A small jQuery extension that handles queuing callbacks to the
existence of a variable, object, or key. You can assign any number of
callbacks to any number of data points that might be affected by
processes running in the background. jQueue listens and waits for
these data you specify to come into existence and then fires off the
correct callback with its arguments.
Not directly: you need a pair getter/setter with an "addListener/removeListener" interface of some sort... or an NPAPI plugin (but that's another story altogether).
A rather simple and simplistic solution is to just use a function call to set the value of the global variable, and never set its value directly. This way you have total control:
var globalVar;
function setGlobalVar(value) {
globalVar = value;
console.log("Value of globalVar set to: " + globalVar);
//Whatever else
}
There is no way to enforce this, it just requires programming discipline... though you can use grep (or something similar) to check that nowhere does your code directly set the value of globalVar.
Or you could encapsulate it in an object and user getter and setter methods... just a thought.
With the help of getter and setter, you can define a JavaScript class that does such a thing.
First, we define our class called MonitoredVariable:
class MonitoredVariable {
constructor(initialValue) {
this._innerValue = initialValue;
this.beforeSet = (newValue, oldValue) => {};
this.beforeChange = (newValue, oldValue) => {};
this.afterChange = (newValue, oldValue) => {};
this.afterSet = (newValue, oldValue) => {};
}
set val(newValue) {
const oldValue = this._innerValue;
// newValue, oldValue may be the same
this.beforeSet(newValue, oldValue);
if (oldValue !== newValue) {
this.beforeChange(newValue, oldValue);
this._innerValue = newValue;
this.afterChange(newValue, oldValue);
}
// newValue, oldValue may be the same
this.afterSet(newValue, oldValue);
}
get val() {
return this._innerValue;
}
}
Assume that we want to listen for money changes, let's create an instance of MonitoredVariable with initial money 0:
const money = new MonitoredVariable(0);
Then we could get or set its value using money.val:
console.log(money.val); // Get its value
money.val = 2; // Set its value
Since we have not defined any listeners for it, nothing special happens after money.val changes to 2.
Now let's define some listeners. We have four listeners available: beforeSet, beforeChange, afterChange, afterSet.
The following will happen sequentially when you use money.val = newValue to change variable's value:
money.beforeSet(newValue, oldValue);
money.beforeChange(newValue, oldValue); (Will be skipped if its value not changed)
money.val = newValue;
money.afterChange(newValue, oldValue); (Will be skipped if its value not changed)
money.afterSet(newValue, oldValue);
Now we define afterChange listener which be triggered only after money.val has changed (while afterSet will be triggered even if the new value is the same as the old one):
money.afterChange = (newValue, oldValue) => {
console.log(`Money has been changed from ${oldValue} to ${newValue}`);
};
Now set a new value 3 and see what happens:
money.val = 3;
You will see the following in the console:
Money has been changed from 2 to 3
For full code, see https://gist.github.com/yusanshi/65745acd23c8587236c50e54f25731ab.
In my case, I was trying to find out if any library I was including in my project was redefining my window.player. So, at the begining of my code, I just did:
Object.defineProperty(window, 'player', {
get: () => this._player,
set: v => {
console.log('window.player has been redefined!');
this._player = v;
}
});
Based On akira's answer I added that you can manipulate the dom through the listerner.
https://jsfiddle.net/2zcr0Lnh/2/
javascript:
x = {
aInternal: 10,
aListener: function(val) {},
set a(val) {
this.aInternal = val;
this.aListener(val);
},
get a() {
return this.aInternal;
},
registerListener: function(listener) {
this.aListener = listener;
}
}
x.registerListener(function(val) {
document.getElementById('showNumber').innerHTML = val;
});
x.a = 50;
function onClick(){
x.a = x.a + 1;
}
html:
<div id="showNumber">
</div>
<button onclick="onClick()">
click me to rerender
</button>
The registerListener method is fired when the variable x.a changes.
//ex:
/*
var x1 = {currentStatus:undefined};
your need is x1.currentStatus value is change trigger event ?
below the code is use try it.
*/
function statusChange(){
console.log("x1.currentStatus_value_is_changed"+x1.eventCurrentStatus);
};
var x1 = {
eventCurrentStatus:undefined,
get currentStatus(){
return this.eventCurrentStatus;
},
set currentStatus(val){
this.eventCurrentStatus=val;
//your function();
}
};
or
/* var x1 = {
eventCurrentStatus:undefined,
currentStatus : {
get : function(){
return Events.eventCurrentStatus
},
set : function(status){
Events.eventCurrentStatus=status;
},
}*/
console.log("eventCurrentStatus = "+ x1.eventCurrentStatus);
x1.currentStatus="create"
console.log("eventCurrentStatus = "+ x1.eventCurrentStatus);
x1.currentStatus="edit"
console.log("eventCurrentStatus = "+ x1.eventCurrentStatus);
console.log("currentStatus = "+ x1.currentStatus);
or
/* global variable ku*/
var jsVarEvents={};
Object.defineProperty(window, "globalvar1", {//no i18n
get: function() { return window.jsVarEvents.globalvarTemp},
set: function(value) { window.window.jsVarEvents.globalvarTemp = value; }
});
console.log(globalvar1);
globalvar1=1;
console.log(globalvar1);
Please guys remember the initial question was for VARIABLES, not for OBJECTS ;)
in addition to all answers above, I created a tiny lib called forTheWatch.js,
that use the same way to catch and callback for changes in normal global variables in javascript.
Compatible with JQUERY variables, no need to use OBJECTS, and you can pass directly an ARRAY of several variables if needed.
If it can be helpful... :
https://bitbucket.org/esabora/forthewatch Basically you just have to call the function :
watchIt("theVariableToWatch", "varChangedFunctionCallback");
And sorry by advance if not relevant.
The question is about variables, not object properties! So my approach is to take advantage of the window object, with its custom getters/setters, and then use/change the variable like a "normal" variable (not like an object property).
The simplest way is that of #José Antonio Postigo in his answer (i voted that answer). What I'd like to do here, is to reduce that to an even simpler "creator" function (so even someone that does not understand object getters/setters can easily use it).
A live example is here: https://codepen.io/dimvai/pen/LYzzbpz
This is the general "creator" function you must have as is:
let createWatchedVariable = (variableName,initialValue,callbackFunction) => {
// set default callback=console.log if missing
callbackFunction ??= function(){console.log(variableName+" changed to " + window[variableName])};
// the actual useful code:
Object.defineProperty(window, variableName, {
set: function(value) {window["_"+variableName] = value; callbackFunction()},
get: function() {return window["_"+variableName]}
});
window[variableName]=initialValue??null;
};
Then, instead of declaring the variable using var or let, use this:
// 1st approach - default callback//
createWatchedVariable ('myFirstVariable',12);
// instead of: let myFirstVariable = 12;
Or, in order to use your custom callback (instead of the default console.log) use:
// 2nd approach - set a custom callback//
var myCallback = ()=>{/*your custom code...*/}
// now use callback function as the third optional argument
createWatchedVariable('mySecondVariable',0,myCallback);
That's it! Now, you can change it like a "normal" variable:
myFirstVariable = 15; // logs to console
myFirstVariable++; // logs to console
mySecondVariable = 1001; // executes your custom code
mySecondVariable++; // executes your custom code
The solution of #akira and #mo-d-genesis can be further simplified because the DOM manipulation does not depend on state in this example:
CodePen
const render = (val) => {
document.getElementById("numberDiv").innerHTML = val;
};
state = {
_value_internal: undefined,
set value(val) {
// 1. set state value
this._value_internal = val;
// 2. render user interface
render(val);
},
get value() {
return this._value_internal;
},
};
const onClick = () => {
state.value = state.value + 1; // state change leads to re-render!
};
// set default value
state.value = 0;
The corresponding html:
<div id="numberDiv"></div>
<button onclick="onClick()">
Click to rerender
</button>
Remarks:
I renamed variables and functions to better reflect their semantics.
FYI: Svelte offers a very similar reactive behavior by changing variables
It's not directly possible.
However, this can be done using CustomEvent: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent
The below method accepts an array of variable names as an input and adds event listener for each variable and triggers the event for any changes to the value of the variables.
The Method uses polling to detect the change in the value. You can increase the value for timeout in milliseconds.
function watchVariable(varsToWatch) {
let timeout = 1000;
let localCopyForVars = {};
let pollForChange = function () {
for (let varToWatch of varsToWatch) {
if (localCopyForVars[varToWatch] !== window[varToWatch]) {
let event = new CustomEvent('onVar_' + varToWatch + 'Change', {
detail: {
name: varToWatch,
oldValue: localCopyForVars[varToWatch],
newValue: window[varToWatch]
}
});
document.dispatchEvent(event);
localCopyForVars[varToWatch] = window[varToWatch];
}
}
setTimeout(pollForChange, timeout);
};
let respondToNewValue = function (varData) {
console.log("The value of the variable " + varData.name + " has been Changed from " + varData.oldValue + " to " + varData.newValue + "!!!");
}
for (let varToWatch of varsToWatch) {
localCopyForVars[varToWatch] = window[varToWatch];
document.addEventListener('onVar_' + varToWatch + 'Change', function (e) {
respondToNewValue(e.detail);
});
}
setTimeout(pollForChange, timeout);
}
By calling the Method:
watchVariables(['username', 'userid']);
It will detect the changes to variables username and userid.
This is what I did: Call JSON.stringify twice and compare the two strings...
Drawbacks:
You can only know whether the whole object changes
You have to detect changes manually
You better have only primitive fields in the object(no properties, no functions...)
This is NOT a production ideal answer, but what it is doing is setting an interval in JavaScript for every 100 milliseconds and checking to see if the variable is changed and when it is, it does something (anything intended by the OP) and then clears the interval, so it sort of simulates what the OP is asking.
let myvar = "myvar";
const checkChange = setInterval(() => {
if (myvar !== "myvar") {
console.log("My precious var has been changed!");
clearInterval(checkChange);
}
}, 100);
Now if myvar gets changed to something else then this program will say "My precious var has been changed!" :)
This is an old great question, has more than 12 years. Also, there are many ways to solve it. However, most of then are complicated or using old JS concepts we are in 2022 and we can use ES6 to improve our code.
I will implemented two main solutions that I constantly use.
Simple variable
If we have a simple variable and we don't care about reutilization then we can declare our variable as an object. We define a set and get methods and a listener attribute to handle the "change" event.
const $countBtn = document.getElementById('counter')
const $output = document.getElementById('output')
const counter = {
v: 0,
listener: undefined,
set value(v) {
this.v = v
if (this.listener) this.listener(v)
},
get value() { return this.v },
count() { this.value++ },
registerListener(callback) {
this.listener = callback
},
}
const countOnClick = () => { counter.count() }
$countBtn.onclick = countOnClick
counter.registerListener(v => {
$output.textContent = v
})
counter.value = 50
#output {
display: block;
font-size: 2em;
margin-top: 0.67em;
margin-bottom: 0.67em;
margin-left: 0;
margin-right: 0;
font-weight: bold;
}
<button id="counter">Count</button>
<div id="output"></div>
Advanced Class for reusability
If we will have multiple variables and we need to monitor them, we can create a class and then apply it to our variables. I recommend to add two listeners one beforeChange and afterChange this will give you flexibility to use the variable in different process.
class ObservableObject {
constructor(v) {
this.v = v ?? 0
this.on = {
beforeChange(newValue, oldValue) {},
afterChange(newValue, oldValue) {},
}
}
set value(newValue) {
const oldValue = this.v
// newValue, oldValue are the same
if (oldValue === newValue) return
this.on.beforeChange(newValue, oldValue)
this.v = newValue
this.on.afterChange(newValue, oldValue)
}
get value() { return this.v }
}
const $countABtn = document.getElementById('counter-a')
const $countBBtn = document.getElementById('counter-b')
const $outputA = document.getElementById('output-a')
const $outputB = document.getElementById('output-b')
const counterA = new ObservableObject()
const counterB = new ObservableObject()
const countOnClick = counter => { counter.value++ }
const onChange = (v, output) => { output.textContent = v }
$countABtn.onclick = () => { countOnClick(counterA) }
$countBBtn.onclick = () => { countOnClick(counterB) }
counterA.on.afterChange = v => { onChange(v, $outputA) }
counterB.on.afterChange = v => { onChange(v, $outputB) }
counterA.value = 50
counterB.value = 20
.wrapper {
display: flex;
flex-flow: row wrap;
justify-content: center;
align-items: center;
width: 100vw
}
.item {
width: 50%
}
.output {
display: block;
font-size: 2em;
margin-top: 0.67em;
margin-bottom: 0.67em;
margin-left: 0;
margin-right: 0;
font-weight: bold;
}
<div class="wrapper">
<div class="item">
<button id="counter-a">Count A</button>
<div id="output-a" class="output"></div>
</div>
<div class="item">
<button id="counter-b">Count B</button>
<div id="output-b" class="output"></div>
</div>
</div>
This is an old thread but I stumbled onto second highest answer (custom listeners) while looking for a solution using Angular. While the solution works, angular has a better built in way to resolve this using #Output and event emitters. Going off of the example in custom listener answer:
ChildComponent.html
<button (click)="increment(1)">Increment</button>
ChildComponent.ts
import {EventEmitter, Output } from '#angular/core';
#Output() myEmitter: EventEmitter<number> = new EventEmitter<number>();
private myValue: number = 0;
public increment(n: number){
this.myValue += n;
// Send a change event to the emitter
this.myEmitter.emit(this.myValue);
}
ParentComponent.html
<child-component (myEmitter)="monitorChanges($event)"></child-component>
<br/>
<label>{{n}}</label>
ParentComponent.ts
public n: number = 0;
public monitorChanges(n: number){
this.n = n;
console.log(n);
}
This will now update non parent each time the child button is clicked. Working stackblitz
I came here looking for same answer for node js. So here it is
const events = require('events');
const eventEmitter = new events.EventEmitter();
// Createing state to watch and trigger on change
let x = 10 // x is being watched for changes in do while loops below
do {
eventEmitter.emit('back to normal');
}
while (x !== 10);
do {
eventEmitter.emit('something changed');
}
while (x === 10);
What I am doing is setting some event emitters when values are changed and using do while loops to detect it.
I searched for JavaScript two-way data binding library and came across this one.
I did not succeed to make it work in DOM to variable direction, but in variable to DOM direction it works and that is what we need here.
I have rewritten it slightly, as the original code is very hard to read (for me). It uses
Object.defineProperty, so the second most upvoted answer by Eliot B. at least partially wrong.
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
const dataBind = (function () {
const getElementValue = function (selector) {
let element = document.querySelectorAll(selector)[0];
return 'value' in element ? element.value : element.innerHTML;
};
const setElementValue = function (selector, newValue) {
let elementArray = document.querySelectorAll(selector);
for (let i = 0; i < elementArray.length; i++) {
let element = elementArray[i];
if ('value' in element) {
element.value = newValue;
if (element.tagName.toLowerCase() === 'select'){
let options = element.querySelectorAll('option');
for (let option in options){
if (option.value === newValue){
option.selected = true;
break;
}
}
}
} else {
element.innerHTML = newValue;
}
}
};
const bindModelToView = function (selector, object, property, enumerable) {
Object.defineProperty(object, property, {
get: function () {
return getElementValue(selector);
},
set: function (newValue) {
setElementValue(selector, newValue);
},
configurable: true,
enumerable: (enumerable)
});
};
return {
bindModelToView
};
})();
</script>
</head>
<body>
<div style="padding: 20%;">
<input type="text" id="text" style="width: 40px;"/>
</div>
<script>
let x = {a: 1, b: 2};
dataBind.bindModelToView('#text', x, 'a'); //data to dom
setInterval(function () {
x.a++;
}, 1000);
</script>
</body>
</html>
JSFiddle.
JSFiddle with original code.
In the provided example a property of object x updated by the setInterval and value of text input automatically updated as well. If it is not enough and event is what you looking for, you can add onchange listener to the above input. Input also can be made hidden if needed.
Utils = {
eventRegister_globalVariable : function(variableName,handlers){
eventRegister_JsonVariable(this,variableName,handlers);
},
eventRegister_jsonVariable : function(jsonObj,variableName,handlers){
if(jsonObj.eventRegisteredVariable === undefined) {
jsonObj.eventRegisteredVariable={};//this Object is used for trigger event in javascript variable value changes ku
}
Object.defineProperty(jsonObj, variableName , {
get: function() {
return jsonObj.eventRegisteredVariable[variableName] },
set: function(value) {
jsonObj.eventRegisteredVariable[variableName] = value; handlers(jsonObj.eventRegisteredVariable[variableName]);}
});
}

Cross-Listen to multiple events and trigger callback

I have a list of event names which I need to listen to stored in an array, like so:
var events = ['A', 'B'];
Now, I'm unsure which event will be triggered first and it could be very inconsistent (depends on the HTTP requests that they await) so I can never safely listen to only one of them. So, I need to somehow "cross-listen" to all of them in order to trigger my original callback.
So my idea was to do the following:
Create a listener for A, which creates a listener for B. B's listener triggers the callback.
Create a listener for B, which creates a listener for A. A's listener triggers the callback.
So this would result in 4 listners, which would look something like this (pseudo-code):
var callback = function() { console.log('The callback'); };
Event.on('A', function () {
Event.on('B', callback);
});
Event.on('B', function () {
Event.on('A', callback);
});
So I believe this would solve my issue (there's probably another problem that I'm not seeing here though).
The issue is, I can make this work when there are only 2 events I need to listen to. But what about when I have 3-4 events I want to "cross-listen" to? Lets say we have ['A', 'B', 'C', 'D']. This would obviously require looping through the events. This part is what's confusing me and I'm not sure how to proceed. This would need to register a nice combination of events.
This needs to be done in JavaScript.
My imagination and logic is limited in this case.
I was thinking something like this:
var callback = function() { console.log('The callback'); };
var events = {
'click': false,
'mouseover': false,
'mouseout': false
};
for(prop in events) {
$('.evt-button').on(prop, function(evt) {
if(events[evt.type] === false) {
console.log('First ' + evt.type + ' event');
events[evt.type] = true;
checkAll();
}
});
}
function checkAll() {
var anyFalse = false;
for(prop in events) {
if(events.hasOwnProperty(prop)) {
if(events[prop] === false) {
anyFalse = true;
break;
}
}
}
if(!anyFalse) {
callback();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button class="evt-button">The button</button>
There's lots of ways to do what you're asking, but to keep it simple you could have an array of event names, as you already do, and simply remove them as they occur, checking to see if the array is empty each time. Like this...
var events = ['A', 'B'];
var callback = function() { console.log('The callback'); };
var eventOccured = function(eventName) {
// if the event name is in the array, remove it...
var idx = events.indexOf(eventName);
if (idx !== -1) {
events.splice(events.indexOf(idx), 1);
}
// if the event array is empty then we've handled everything...
calback();
};
Event.on('A', function () {
// do whatever you need in the event handler
eventOccured("A");
});
Event.on('B', function () {
// do whatever you need in the event handler
eventOccured("B");
});
A bit late, but you can make a function that wraps your callback and reuse it to attach multiple eventlisteners and count until all have occurred. This way you can also add events to cancel out others, say keyup cancels keydown.
const K = a => _b => a
const makeEventTrigger = (fn) => {
let lastTarget,
required = 0,
active = 0;
return (enable, qualifier = K(true)) => {
required = enable ? required + 1 : required;
return (event) => {
if(!qualifier(event)) {
return
}
const isLastTarget =
lastTarget && lastTarget.isEqualNode(event.currentTarget);
if (!enable) {
lastTarget = isLastTarget ? null : lastTarget;
active = Math.max(0, active - 1);
return;
}
if (!isLastTarget) {
lastTarget = event.currentTarget;
active = Math.min(required, active + 1);
return active === required && fn();
}
};
};
};
let changeTitleCol = () =>
(document.querySelector("h1").style.color =
"#" + Math.random().toString(16).slice(-6));
let addTriggerForColorChange = makeEventTrigger(changeTitleCol);
let isSpace = e => e.key === " " || e.code === "Space"
document
.querySelector("button")
.addEventListener("mousedown", addTriggerForColorChange(true));
document
.querySelector("button")
.addEventListener("mouseup", addTriggerForColorChange(false));
document.addEventListener("keydown", addTriggerForColorChange(true, isSpace));
document.addEventListener("keyup", addTriggerForColorChange(false));
<h1>Multiple Event sources!</h1>
<div>
<button id="trigger-A">klik me and press space</button>
</div>

How do I know when a DOM-element is created?

I'm trying to acquire a reference for a specific QUnit DOM-element, as soon as this element is created. I can get it by using window.setTimeout, but is there an event-driven way to do it?
I have tried various approaches, but only the least satisfying (window.setTimeout) actually works:
window.onload = function() {
var qunitTestrunnerToolbar_element = document.getElementById("qunit-testrunner-toolbar");
console.log("from window.onload: qunitTestrunnerToolbar_element: ", qunitTestrunnerToolbar_element);
};
returns null
document.addEventListener("DOMContentLoaded", function(event) {
var qunitTestrunnerToolbar_element = document.getElementById("qunit-testrunner-toolbar");
console.log("from document.addEventListener(DOMContentLoaded): qunitTestrunnerToolbar_element: ", qunitTestrunnerToolbar_element);
});
returns null
document.addEventListener("load", function(event) {
var qunitTestrunnerToolbar_element = document.getElementById("qunit-testrunner-toolbar");
console.log("from document.addEventListener(load): qunitTestrunnerToolbar_element: ", qunitTestrunnerToolbar_element);
});
is never executed
window.setTimeout(function() {
var qunitTestrunnerToolbar_element = document.getElementById("qunit-testrunner-toolbar");
console.log("from window.setTimeout: qunitTestrunnerToolbar_element: ", qunitTestrunnerToolbar_element);
}, 2000);
returns the DOM-reference
The code can be befiddled at this jsfiddle.
Note that the fiddle only logs the one successful DOM-reference. The others are somehow silenced.
This is how it looks when executed locally:
There is the DOMMutationObserver, which allows you to subscribe to changes to the DOM.
var mutationObserver = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
var id = 'qunit-testrunner-toolbar',
added = mutation.addedNodes,
removed = mutation.removedNodes,
i, length;
for (i = 0, length = added.length; i < length; ++i) {
if (added[i].id === id) {
// qunit-testrunner-toolbar was added
}
}
for (i = 0, length = removed.length; i < length; ++i) {
if (removed[i].id === id) {
// qunit-testrunner-toolbar was removed
}
}
});
});
mutationObserver.observe(target, {childList: true});
If you need to stop listening for changes (as the amount of changes to the DOM can be huge ;) ), you can simply use mutationObserver.disconnect().
If the #qunit-testrunner-toolbar is not the node that is added (but instead is part of another structure), the checks above will not work. If that is the case you can replace the added[i].id === id with something like
if (added[i].querySelector('#qunit-testrunner-toolbar')) {
// it was added
}
I should at least mention the now deprecated Mutation Events, which seem more convenient to implement but were pretty slow and inaccurate.
document.addEventListener('DOMNodeInserted', function(e) {
if (e.target.id === 'qunit-testrunner-toolbar') {
}
});
Tempting to use, but don't as it is deprecated.
Everything you put in JSFiddle's javascript is already wrapped in onload event (so window.onload will never be fired again - it is already fired). Change it to "Javascript" -> "Load time" -> "No wrap - in <head>" and you will get all of your events fired.

JavaScript custom Event Listener

I was wondering if anyone can help me understand how exactly to create different Custom event listeners.
I don't have a specific case of an event but I want to learn just in general how it is done, so I can apply it where it is needed.
What I was looking to do, just incase some folks might need to know, was:
var position = 0;
for(var i = 0; i < 10; i++)
{
position++;
if((position + 1) % 4 == 0)
{
// do some functions
}
}
var evt = document.createEvent("Event");
evt.initEvent("myEvent",true,true);
// custom param
evt.foo = "bar";
//register
document.addEventListener("myEvent",myEventHandler,false);
//invoke
document.dispatchEvent(evt);
Here is the way to do it more locally, pinpointing listeners and publishers:
http://www.kaizou.org/2010/03/generating-custom-javascript-events/
Implementing custom events is not hard. You can implement it in many ways. Lately I'm doing it like this:
/***************************************************************
*
* Observable
*
***************************************************************/
var Observable;
(Observable = function() {
}).prototype = {
listen: function(type, method, scope, context) {
var listeners, handlers;
if (!(listeners = this.listeners)) {
listeners = this.listeners = {};
}
if (!(handlers = listeners[type])){
handlers = listeners[type] = [];
}
scope = (scope ? scope : window);
handlers.push({
method: method,
scope: scope,
context: (context ? context : scope)
});
},
fireEvent: function(type, data, context) {
var listeners, handlers, i, n, handler, scope;
if (!(listeners = this.listeners)) {
return;
}
if (!(handlers = listeners[type])){
return;
}
for (i = 0, n = handlers.length; i < n; i++){
handler = handlers[i];
if (typeof(context)!=="undefined" && context !== handler.context) continue;
if (handler.method.call(
handler.scope, this, type, data
)===false) {
return false;
}
}
return true;
}
};
The Observable object can be reused and applied by whatever constructor needs it simply by mixng the prototype of Observable with the protoype of that constructor.
To start listening, you have to register yourself to the observable object, like so:
var obs = new Observable();
obs.listen("myEvent", function(observable, eventType, data){
//handle myEvent
});
Or if your listener is a method of an object, like so:
obs.listen("myEvent", listener.handler, listener);
Where listener is an instance of an object, which implements the method "handler".
The Observable object can now call its fireEvent method whenever something happens that it wants to communicate to its listeners:
this.fireEvent("myEvent", data);
Where data is some data that the listeners my find interesting. Whatever you put in there is up to you - you know best what your custom event is made up of.
The fireEvent method simply goes through all the listeners that were registered for "myEvent", and calls the registered function. If the function returns false, then that is taken to mean that the event is canceled, and the observable will not call the other listeners. As a result the entire fireEvent method will return fasle too so the observable knows that whatever action it was notifying its listeners of should now be rolled back.
Perhaps this solution doesn't suit everybody, but I;ve had much benefit from this relatively simple piece of code.
From here:
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
// create the event
const event = new Event('build');
// elem is any element
elem.dispatchEvent(event);
// later on.. binding to that event
// we'll bind to the document for the event delegation style.
document.addEventListener('build', function(e){
// e.target matches the elem from above
}, false);
Here is a really simple (TypeScript/Babelish) implementation:
const simpleEvent = <T extends Function>(context = null) => {
let cbs: T[] = [];
return {
addListener: (cb: T) => { cbs.push(cb); },
removeListener: (cb: T) => { let i = cbs.indexOf(cb); cbs.splice(i, Math.max(i, 0)); },
trigger: (<T> (((...args) => cbs.forEach(cb => cb.apply(context, args))) as any))
};
};
You use it like this:
let onMyEvent = simpleEvent();
let listener = (test) => { console.log("triggered", test); };
onMyEvent.addListener(listener);
onMyEvent.trigger("hello");
onMyEvent.removeListener(listener);
Or in classes like this
class Example {
public onMyEvent = simpleEvent(this);
}
If you want plain JavaScript you can transpile it using TypeScript playground.

Javascript: Check if Element has Changed

I want to know, if it's possible, how to check in javascript if an element has changed or an attribute of it?
I mean something like window.onhashchange for an element something like:
document.getElementById("element").onElementChange = function();
As I know onchange is something like this, but will it work if I want to know in this way:
var element = {};
element.attribute = result;
element.attribute.onchange = function();
As far as I understand you want onChange on javascript object Properties. The answer is no, it doesn't exist as far as I know.
But you can make a setter function like this (As a proof of concept):
var element = {};
element.setProperty = function(property, value) {
if (typeof(element.onChange) === 'function') {
element.onChange(property, element[property], value);
}
element[property] = value;
};
element.onChange = function(property, oldValue, newValue) {
alert(property + ' changed from ' + oldValue + ' to ' + newValue);
};
element.setProperty('something', 'Hello world!');
now you get an alert box with 'something changed from undefined to Hello World!'. And (element.something === 'Hello World!') will return true.
if you now call:
element.setProperty('something', 'Goodbye world!');
you get an alert box with 'something changed from Hello World! to Goodbye World!'.
Off course you have to set the property only via the setProperty method in all of your code if you want to capture this event!
Edit:
At some time in the future, you might be able to use Object.observe().
Edit 2:
Now there's also proxies.
You might consider a mutation observer.
to do this you first create a callback (fired when the dom element changes)
assign it to an observer var observer = new MutationObserver(callback);
Then tell the observer what to watch observer.observe('<div></div>', observerOptions);
From:
Mozilla page on Mutation Observers
I guess you'd need a way to capture the event which triggered the change in attribute rather than the change in attribute. The change in attribute could only either be due to your CSS or your javascript, both being manifestations of the user's actions.
I believe there is no such event. However, you can use setInterval or setTimeout to watch for element changes and use it to react accordingly.
I did this. It works pretty well. I would have used the setProperty method if I had known.
function searchArray(searchValue, theArray, ChangeValue){
for (var i=0; i < theArray.length; i++) {
if (theArray[i].id === searchValue) {
theArray[i].changed = ChangeValue;
}
}
}
function getArrayIindex(elementid, theArray){
for (var i=0; i < theArray.length; i++) {
if (theArray[i].id === elementid) {
return i;
}
}
}
function setInputEvents(hiddenObject) {
var element;
for (var i = 0; i < document.forms[0].length; i++) {
element = document.forms[0].elements[i];
//Check to see if the element is of type input
if (element.type in { text: 1, password: 1, textarea: 1 }) {
arrFieldList.push({
id: element.id,
changed:false,
index: i,
});
element.onfocus = function () {
if (!arrFieldList[getArrayIindex(this.id, arrFieldList)].changed) {
hiddenObject.value = this.value;
this.value = '';
}
}
element.onblur = function () {
if (this.value == '') {
this.value = hiddenObject.value;
}
}
element.onchange = function () {
searchArray(this.id, arrFieldList, true);
}
}
}

Categories

Resources