Wednesday, 5 August 2009

Easy binding in Javascript

 

Felt like writing a framework that could bind the contents of an arbitrary html div to a javascript function. This is what I came up with. It is an evil use of eval. Any advances?

 

<html>
<
head>
<body>



<div id="myDiv" binding="myValue" changed="flash"></div>


<script type="text/javascript">


function myValue(){return "hello first value"};

var checkBindings= function(){
var elements = document.getElementsByTagName('*');
for (var i = 0; i < elements.length; i++) {

//look for the binding attribute on the element
var bindingFunction = elements[i].getAttribute("binding");
if (bindingFunction != null){
//eval the bound function, which must take no parameters
newHtml = eval (bindingFunction+"();");

//has it changed?
var changed = newHtml != elements[i].innerHTML

//update it
elements[i].innerHTML=newHtml;

//if it's changed, call the function, passing in the changed element
if (changed){
var changedFunction = elements[i].getAttribute("changed");
if (changedFunction != null){
eval(changedFunction+"(elements[i])");
}
}

}
}
//call this again in four seconds
setTimeout(checkBindings,4000);
}

//a function to fire on a changed event
function flash(element){
element.style.backgroundColor="#aa0000";
setTimeout(function(){element.style.backgroundColor="#ffffff"},3000);
}


//run the script 
checkBindings();
</script>

</
body>

</
html>


Tim Stevens

Tim Stevens
Work
Consume
Obey
Be Silent
Die