I have a single page application I'm working on in which a variable x can change for many reasons. I want the value displayed in the DOM (the div below) to at all times match the value of the javascript variable.
I understand frameworks like angular are good for this, but I'm looking for a more lightweight and simple solution. I'm already using JQuery and underscore.js on the page if that helps.
<script>
var x = 100
</script>
<div id="value_display">100</div>
Ideally I'd like something where I just need to provide the variable and the element as arguments. For example:
bind(x,'#value_display')
From View to Component One-way data binding from view to the component can be achieved by using the event binding technique.
In one-way data binding information flows in only one direction, and is when the information is displayed, but not updated. In two-way data binding information flows in both directions, and is used in situations where the information needs to be updated. They each have their uses, but most applications use both.
One-way data binding in Angular (i.e. unidirectional binding) is a way to bind data from the component to the view (DOM) or vice versa - from view to the component. It is used to display information to the end-user which automatically stays synchronized with each change of the underlying data.
Eg. with one way data flow, if you don't log the mutations, you don't have that trace to help you debug. And with two way data binding, the framework could be written such that it logs the view → model mutations when the model is automatically updated, just like Redux does.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With