2

I know a lot of the big name MVC, M** style JavaScript frameworks allow 2-way binding with Observables.

Meaning if I:

  • Update a DOM input filed, it will also update a JavaScript object variable which could also save to server with AJAX request.
  • If I update the JavaScript object variable, it will also in turn update the DOM text field.

As I am learning JavaScript, I would love to skip the big name libraries and learn how to do this in it's most basic raw JavaSript form.

Can anyone provide quick easy to understand demo of this functionality without using libraries like BackboneJS, Knockout, Angular, or others?

jQuery is acceptable.

I would appreciate the lesson and help please.

Dave Riley
  • 191
  • 1
  • 7
  • I don't have time to write a full answer, but you might want to take a look at the Observer design pattern. This is one of the key patterns in MVC and other frameworks. Basically you notify every observer whenever you change the value and the observers then take the new value. You can do this in both ways of course. – Jochem Kuijpers May 16 '15 at 17:17
  • Maybe [KVO](https://parmanoir.com/KVC_and_KVO_from_a_Javascript_standpoint) is a better term in this context – Dr.Molle May 16 '15 at 17:37
  • @Dr.Molle Thanks for sharing I had never heard of it before! – Dave Riley May 16 '15 at 17:43
  • See https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver , https://github.com/jdarling/Object.observe , http://bocoup.com/weblog/javascript-object-observe/ – guest271314 May 16 '15 at 18:02

1 Answers1

0

This is different in every framework.

Angular for instance saves every variable on scopes. Iterate through the scopes variables and compare the values with the previous ones and if there is a change it is carried out to the DOM.

This check is made upon they call digest cycles. If one cycle is finished it calls again until every variable 'observed' is the same as it was in the previous cycle. You can also add objects or vars to this 'observer'.

Angular keeping the view current, with calling this digest every time something could change the 'observed' vars, like http calls, user interactions ... but for instance, if you change a variable outside from angular (console), than the variable change is not carried out to the DOM. You have to call a digest cycle manually to do so.

In HTML5 it is a bit easier with Object.observe, but it is not yet supported in every browser currently on the market.

Hope I could help

lyttlegy
  • 101
  • 5