See the demo here: Data Binding in JavaScript
Back when I was in Flex land one of the things that I found to be really neat was data binding... you could essentially have widgets that would update if the data updated automagically. I also wanted to take a stab at doing publishing and subscribing in YUI3, so built this an object called DB, which stores data. It can do three things, it can set() data, it can get() data, and it's an EventTarget, so you can subscribe to it's change event:
var DB = function (data) { this._d = null; this.publish("change",{emitFacade: true}); this.set = function (data) { this._d = data; this.fire("change"); }; this.get = function () { return this._d; }; this.set(data); }; Y.augment(DB, Y.EventTarget);
And to instantiate an instance of DB you just do var myData = new DB();, and then you can subscribe to it any number of times to be notified when the data has been updated. For example:
<input type="text" id="in1"/> <br/> <input type="text" id="in2"/>
var myData = new DB(); var inputs = Y.all("#in1, #in2"); myData.on("change", function() { inputs.each(function(node) { node.set('value', myData.get()); }); }); inputs.on("keyup", function(ev) { myData.set(ev.currentTarget.get('value')); });
This code is pretty simple. In YUI3 it creates an instance of DB, which has it's own private data (unset initially), subscribes to the change event with a function that updates both text inputs on the page if myData gets set(), and then binds to the keyup event on the text inputs to call myData.set() whenever the contents of either text input has something typed into it. This results in a page where both inputs update whenever you type into either one.
See the demo here: Data Binding in JavaScript
Is this useful? Practical? UnJavaScripty? I don't know, but I'd love to hear what you think
April 16th, 2010 at 2:39 pm
You should look at ExtJS’ Record and Data Store objects for a very elegant implementation of this pattern.
JS
April 17th, 2010 at 7:56 am
I think the pattern is quite interesting and could be somehow useful in some edge situations .. I do like the idea of being able to bind events to data.
However maybe that’s because I’m from jQueryland but, that seems a whole lot of code to perform a relatively simple task..
The single most advantage I can see of this method is achieving near perfect plugin encapsulation.
April 20th, 2010 at 12:16 pm
I heavily use this type of databinding and more in mobl (http://zef.me/3117/mobl-screencast-1-todo-application). An extreme implementation of it is called reactive programming and used in for instance spreadsheets (http://zef.me/3098/reactive-programming).