Native Data-binding using JavaScript with observe

We have always loved using MV* frameworks for data-binding. Well, we have our reasons. There was never an easy way to set event listeners on RAW objects and perform certain tasks. Thanks to the recent ECMASCRIPT’s (7.0) proposal, data-binding has never been so easy and best of all, without any help from any framework.

Announcing Object/Array.observe

Allow me to introduce you to

a method that asynchronously keeps track of the changes to the data model or
simply an array which allows you to perform certain tasks by providing a callback function every time it detects a change in your data model.

This callback function returns an object that provides the following information.

  1. type of change(add, update, delete) and splice if you are calling observe on an array
  2. name of the property changed
  3. changed object
  4. and the old value of the changed property

Why are we going gaga over data-binding? Well, data-binding is important if you care about keeping the content, presentation and behavior separate. HTML is perfect for declaring static documents and therefore, we need a way to tie our document and data together. With data-binding, we achieve just that. Using Object/Array.observe, we observe the changes in our data model and keep the DOM upto date.

Without further ado, let me show you how easy it is.

Note: Following example uses handlebars (which depends on jQuery) to save me from writing unnecessary DOM manipulation code.

  <!DOCTYPE html>
  <meta charset=”utf-8″>
  <title>Data-binding with object.observe</title>
  <script src=”//”></script>
  <script src=”//”></script>
  <script id=”handlebars-template” type=”text/x-handlebars-template”>
  <div id=”output”>
  var source = $(“#handlebars-template”).html();
  var template = Handlebars.compile(source);
  // Our data model
  var DataModel = {
  yearsRocking: 0,
  name: “Robert Plant”,
  occupation: “Rocking”
  // takes the compiled output and dumps it onto the body
  function updateDOM() {
  var html = template(DataModel);
  // init
  // dumping the compiled output from handlebars template onto the body
  // Observing changes on the data model
  // Checking if id value has been changed
  // and if yes, updating the DOM
  Object.observe(DataModel, function(changes) {
  changes.forEach(function(change) {
  if( === ‘yearsRocking’) {
  // Simplest way to make changes to the data model
  DataModel.yearsRocking += 1;
  }, 1000);

view rawdata-binding-with-object.observe.html hosted with ❤ by GitHub


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.