DGwang DGwang - 2 months ago 15
Javascript Question

Javascript 2 way data binding, Not framework

I am just trying to understand data binding in pure javascript. When I create an input and attach an event listener such as 'input' and then call a function to replace the innerHTML of a div with that new input value, the div will mirror the input box as I am typing.

I am trying to get the div to update when the value of the input box changes without someone typing. So if the input were to change because of some code:

inp.value = 'Testing'


instead of someone directly typing inside of it, I would like the text within the div to still mirror it.

I tried it with the 'change' event listener but that only works when the input box loses focus. So I tried adding that into the code:

inp.focus();
inp.value = 'Testing';
inp.blur();


But that doesn't work either.

Here is a link to my jsfiddle:
https://jsfiddle.net/mmpal78/7g0vqwgh/1/

I am guessing there must be a way to do this. Thanks.

Answer

So if the input were to change because of some code:

inp.value = 'Testing'

instead of someone directly typing inside of it, I would like the text within the div to still mirror it.

You can't do that, there is no event raised when value is set that way, nor will a MutationObserver see anything to report.

Instead, you either

  • Disallow direct access (just as a policy thing) and have all setting go through your framework (and then have your framework update anything affected by the value change). KO does this by having you work through its "obervables." Or,
  • Update at whatever you consider appropriate times, such as whenever you're done processing an event, probably by storing the latest value of value you've processed and then checking it against the current value. Angular 1 did something like that. Or,
  • Explicitly update anything you know is affected by value in the code modifying value (but that doesn't scale, you will forget to do it).