Easy Two-Way Data Binding in JavaScript

523

wo-way data binding refers to the ability to bind changes to an object’s properties to changes in the UI, and viceversa. In other words, if we have a user object with a name property, whenever we assign a new value to user.name the UI should show the new name. In the same way, if the UI includes an input field for the user’s name, entering a value should cause the name property of the user object to be changed accordingly.

Many popular client-side JavaScript frameworks like Ember.js, Angular.js or KnockoutJS advertise two-way data binding among their top features. This doesn’t mean that it is too hard to implement it from scratch, nor that adopting one of those frameworks is the only option when this kind of functionality is needed. The underlying idea is in fact quite basic, and can be condensed into a 3-point action plan:

  1. We need a way to specify which UI elements are bound to which properties
  2. We need to monitor changes on the properties and on the UI elements
  3. We need to propagate any change to all bound objects and elements

While there are multiple ways to achieve this, a simple and efficient approach makes use of the PubSub pattern. The idea is simple: we can use custom data attributes to specify bindings in the HTML code. All JavaScript objects and DOM elements that are bound together will “subscribe” to a PubSub object. Anytime a change is detected on either the JavaScript object or on an HTML input element, we proxy the event to the PubSub, which in turn broadcasts and propagates the change on all the other bound objects and elements.

Reference: http://www.lucaongaro.eu/blog/2012/12/02/easy-two-way-data-binding-in-javascript/