Created
December 7, 2012 10:30
-
-
Save maurodoglio/4232367 to your computer and use it in GitHub Desktop.
Mauro's observer - updated to create two models
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> | |
<title>My js observer</title> | |
<script type="text/javascript"> | |
"use strict"; | |
var Model = function(){ | |
this.observers = []; | |
this.value = null | |
}; | |
Model.prototype = { | |
'get' : function(){ | |
return this.value; | |
}, | |
'set' : function(value){ | |
this.value = value; | |
this.notify_observers(); | |
}, | |
'notify_observers' : function(){ | |
for (var i=0;i<this.observers.length;i++){ | |
this.observers[i](this.value); | |
} | |
}, | |
'register' : function(callback){ | |
this.observers.push(callback); | |
} | |
} | |
function updateValue(id, value) { | |
var elem = document.getElementById(id); | |
elem.innerHTML = value; | |
} | |
function update_div1(value){ | |
updateValue('div1', value); | |
} | |
function update_div2(value){ | |
updateValue('div2', value); | |
} | |
function update_div3(value){ | |
updateValue('div3', value); | |
} | |
function update_div4(value){ | |
updateValue('div4', value); | |
} | |
function init(){ | |
var firstModel = new Model(); | |
firstModel.register(update_div1); | |
firstModel.register(update_div2); | |
firstModel.set('Should only affect divs 1 and 2'); | |
var secondModel = new Model(); | |
secondModel.register(update_div3); | |
secondModel.register(update_div4); | |
secondModel.set('Should only affect divs 3 and 4'); | |
} | |
</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> | |
<div id="div3">I'm the third div</div> | |
<div id="div4">I'm the forth div</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment