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.
- type of change(add, update, delete) and splice if you are calling observe on an array
- name of the property changed
- changed object
- 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> | |
<html> | |
<head> | |
<meta charset=“utf-8“> | |
<title>Data-binding with object.observe</title> | |
</head> | |
<body> | |
<script src=“//code.jquery.com/jquery-1.9.1.min.js“></script> | |
<script src=“//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0/handlebars.js“></script> | |
<script id=“handlebars-template“ type=“text/x-handlebars-template“> | |
<div id=“output“> | |
<h1>{{name}}</h1> | |
<h2>{{yearsRocking}}</h2> | |
<div>{{occupation}}</div> | |
</div> | |
</script> | |
<script> | |
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); | |
$(‘body‘).html(html); | |
} | |
// init | |
// dumping the compiled output from handlebars template onto the body | |
updateDOM(); | |
// 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(change.name === ‘yearsRocking‘) { | |
updateDOM(); | |
console.log(change); | |
} | |
}); | |
}); | |
// Simplest way to make changes to the data model | |
setInterval(function(){ | |
DataModel.yearsRocking += 1; | |
}, 1000); | |
</script> | |
</body> | |
</html> |