Bi-directional data-binding method that ties properties on an object model to DOM elements.
Pass a POJO (Plain Old Javascript Object) as a model, a property name and a list of DOM elements and they will be bound for time and all eternity... or until you leave the page. Updates to the model property will be reflected in the DOM and changing bound form fields will update the model.
This currently weighs in at 206 bytes, but I think it could still be golfed further. A decent chuck is dedicated to handling the logic around dealing with checkbox and radio inputs and there is probably a better way to organize it to avoid/reuse all the inner functions.
Note that this uses the Object.watch method which is only implemented in firefox. A polyfill is provided and is tested to work on the latest Chrome.
Ideas for further enhancement:
- Use Object.observe instead of watch
- Use DOM Mutation Observers instead of onchange/onkeyup handlers (cant happen in under 140 though, too verbose)
- Handle binding to calculated properties, arrays and nested objects
- Add unbind functionality and clean up
See the 140byt.es site for a showcase of entries (built itself using 140-byte entries!), and follow @140bytes on Twitter.
To learn about byte-saving hacks for your own code, or to contribute what you've learned, head to the wiki.
140byt.es is brought to you by Jed Schmidt, with help from Alex Kloss. It was inspired by work from Thomas Fuchs and Dustin Diaz.
Nice work, it never occurred to me to switch to bitwise or and the regex change is slick!
The DOM pollution would not be acceptable in any other context but with code golf I don't feel too bad... it would be unexpected for it to cause any side effects at least.