For data binding in JavaScript, many would turn to tried and true frameworks such as knockout.js or angular.js. I'm by all means not against the use of these, but I love figuring out how to do things on my own. My logic is that by understanding how things work in their most basic form, using a framework will only make things easier when the need arises. I apply this concept to many things in life, such as baking or cooking without a recipe (how do certain ingredients affect the outcome), or fixing broken electronics (which part is responsible for what action). By understanding how things work, you can gain a deeper understanding than by just blindly following instructions.

Which brings me to my main point: how can we achieve data binding without relying on a framework? The Object.observe() method can be used to listen for changes to an object. According to MDN, this method calls your callback every time the object is modified. This may be extremely useful, but browser support is extremely limited for now, with only Chrome 36+ and Opera 23+ having this ability.

Another way to achieve binding is by overriding the getter and setter methods for an object. For example, we have a person object:

var person = {
age: 23,
name: "Michael"
};

And to overwrite the getter or setter for a property, we can use

Object.defineProperty(person, "name", {
get: function() {
return element.innerHTML;
},
set: function(value) {
element.innerHTML = value;
},
configurable: true
});

Now, everytime the name property changes, the element has its HTML changed too. This is an example of data binding to an element without using a framework. I have written a small script that can bind data to multiple elements. This way, we can - for example - bind the name to a textbox and a span, and any modification to the data will be reflected on the bounded elements. An example is on my Github. Obviously, something like angular.js can accomplish this so much easier than my method. With my script, something like iqwerty.binding.bind(person, "name", [ele1, ele2]); must be used, while in angular, simply stating a ng-model="name" attribute in a textbox and {{name}} is enough to bind the data.

I will be working on this data binding script a bit more in my free time, but nothing major will likely happen to it. On another note, I finally created a Github account. I previously always used a git repository on my private dedicated server, but it was a pain to share repositories with. I probably will not have many projects on Github, but it's there, so that's nice :)

May 24, 2015 | 4 comments

Comments

滿特別的寫法!

Winter | May 24, 2015

Thank you :)

Michael | May 28, 2015

Hi !
要幸福唷:-)

lifang | June 3, 2015

Hi 方 :)
妳也要喔

Michael | June 3, 2015
© 2018 Michael Cheng
made in Taiwan