Sexy HTML+JS binding for prototypes
Let's say that you are to create a interactive prototype with quite a lot of different views and states. It has to be done now and you know it will use js plugins that have to be loaded manually.
What if you could just load one JS file and then control its behaviour with pure HTML, like here:
<select data-use="select2" data-config='{"allowClear":true}'>
// options go here
</select>
or:
<div data-use="loadView" data-config='{"model":"pages/test.json", "tpl":"tpl/test.tpl"}'>
</div>
or even:
<input type="email" data-use="placeholderShim" placeholder="Your email">
basically:
<ELEMENT data-use="jquery method name" data-config='{"json config parameter":"value"}'>
# and
<ELEMENT data-use="jquery method name" data-config="config parameter or flag">
Note that, jQuery will convert data-config to js object id attribute starts with {}
And you could create this functionality with just few lines of code:
$(function(){
function addBehaviour(){
var $me = $(this);
$me[$me.data('use')]($me.data('config'));
}
$('[data-use]').each(addBehaviour);
});
Coffeescript version:
$ ->
addBehaviour = ->
$me = $ @
$me[$me.data 'use'] $me.data 'config'
$('[data-use]').each addBehaviour
Or a sweet oneliner:
This way you don't have to call jQuery plugins manually every time page is loaded.
PS. When dealing with JSON in element parameters don't forget to put data in single braces like: <div attribute='value'></div>
. This is as important as using double braces only in JSON.
PPS.
I've stumbled across similar approach when reading Angular UI docs, but there's nothing to stop us when dealing with a different things (with some minor adjustmens, of course).
PPPS.
This isn't a production quality solution. Basically, it's kind of oldschool, if you asked me. If you want to create something that won't be used internally, use a good mvc framework.