Light-weight JSON Binding Framework
Date : 2008 07 30 Category : Tech & DevelopmentIn my other life as a desktop application developer (which due to a mix of Fluid, AIR, Prism, canvas, SVG, and Flash is threatening to converge on my Ajax life) I've long been a fan of data-binding frameworks that make it easy to have a form automatically synchronize with backing data structures, saving you from the tedium of a dozen little "widget.getValue() - dataModel.setValue()" calls (or in the case of grids, etc. much more verbose and tedious plumbing).
Dojo and others frameworks have some interesting binding features, but if your favorite JavaScript framework lacks form data binding, check out Steven Bazyl's small stand-alone JSON binding project: js-binding.
The project is just getting started, but it already has a few basic features that make it useful. For example, to convert this form:
PLAIN TEXT HTML: <form> <input type="text" name="username"/> <input type="text" name="email"/> <input type="text" name="address.street"/> <input type="text" name="address.city"/> <input type="text" name="address.state"/> ... </form>into this object:
PLAIN TEXT JAVASCRIPT: { username: "...", email: "...", address: { street: "...", city: "...", state: "..." } }You just need to write this code:
PLAIN TEXT JAVASCRIPT: var myObject = ...; var myForm = ...; var binder = Binder.FormBinder.bind( myForm ); binder.deserialize( myObject );js-binder also has a built-in type conversion mechanism that, for example, allows you to easily integrate with a JavaScript date parsing library:
PLAIN TEXT JAVASCRIPT: var binder = Binder.FormBinder.bind( myForm, { date: { // Date handler using datejs much improved parsing... parse: function( value ) { return Date.parse( value ); }, format: function( value ) { return Date.toString( 'M/d/yyyy' ); } } } ); binder.deserialize( myObject );The docs are concise but useful.