You ask for a simple implementation (no large frameworks) of an observer pattern, ideally just by providing the variable name and the element's id as arguments.
What you ask for is possible, if we define the bind()
function to repeatedly poll x
to see if it has changed. Note that bind
then has to be called like this:
bind('x','value_display');
A working example:
var x = 100;
function bind(varName, elementId){
var lastValue;
function check(){
if(lastValue !== window[varName]){
lastValue = window[varName];
document.getElementById(elementId).innerHTML = lastValue;
}
}
//poll for changes every 50 milliseconds
setInterval(check, 50);
}
//bind x to value_display
bind('x','value_display');
//test function by changing x every 100th millisecond
setInterval(function(){
x = +new Date;
},
100
);
<div id="value_display"></div>
Personally, I would prefer a lightweight publisher/subscriber module over using a polling function, but that would require assignment to the variable x
to be controlled by a function/method (some kind of setter). If you research (google) observer pattern or pub/sub pattern, you will find easy ways of implementing this in much less code than a large framework—but probably not as lightweight as the polling approach.