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.
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.
Follow me on Twitter