Skip to content

Instantly share code, notes, and snippets.

@maurodoglio
Created December 6, 2012 20:59
Show Gist options
  • Save maurodoglio/4228298 to your computer and use it in GitHub Desktop.
Save maurodoglio/4228298 to your computer and use it in GitHub Desktop.
Mauro's observer
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" dir="ltr">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script type="text/javascript">
var Model = function(){};
Model.prototype = {
'value' : null,
'observers' : [],
'get' : function(){
return this.value;
},
'set' : function(value){
this.value = value;
this.notify_observers();
},
'notify_observers' : function(){
for (i=0;i<this.observers.length;i++){
this.observers[i](this.value);
}
},
'register' : function(callback){
this.observers.push(callback);
}
}
function update_div1(value){
var elem = document.getElementById('div1');
elem.innerHTML = value;
}
function update_div2(value){
var elem = document.getElementById('div2');
elem.innerHTML = value;
}
function init(){
var model = new Model();
model.register(update_div1);
model.register(update_div2);
model.set('First value');
model.set('Second value');
}
</script>
<style type="text/css">
div{height:120px; width: 200px; border:1px solid #000;}
</style>
</head>
<body onload="init()">
<div id="div1">I'm the first div</div>
<div id="div2">I'm the second div</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment