Snippets
Created by
Zsolt Bodnár
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | <!DOCTYPE html>
<html>
<head>
<title>Observer-Subject</title>
<style type="text/css">
td {
height: 100px;
width: 100px;
border: 1px solid black;
}
table {
border: 1px;
border-color: black;
}
</style>
<script type="text/javascript">
window.onload = function(e) {
function Subject(state){
this.state = state;
};
Subject.prototype.observers = new Array();
Subject.prototype.hasIt = function(id) {
var result = this.observers.findIndex(function(elem) {
return (elem.id == id)
});
return result;
}
Subject.prototype.attach = function(input) {
this.observers.push(input);
return false;
};
Subject.prototype.detach = function(id) {
var result = this.observers.findIndex(function(elem) {
return (elem.id == id)
});
this.observers.splice(result, 1);
};
Subject.prototype.notify = function() {
var cellak = document.querySelectorAll("[id^='cella']");
cellak.forEach(function(cella) {
cella.style.background = "white";
});
this.observers.forEach(function(observer) {
observer.update();
})
return false;
};
function Observer(id){
this.id = id
};
Observer.prototype.observerState = "";
Observer.prototype.update = function() {
var str = this.id;
var patt = new RegExp("[0-9]$");
var result = patt.exec(str);
var cella = "cella" + result;
document.getElementById(cella).style.background = "green";
return false;
};
var gombok = document.querySelectorAll("[id^='gomb']");
var subject = new Subject()
gombok.forEach(function(elem) {
var str = elem.id;
var patt = new RegExp("[0-9]$");
var result = patt.exec(str);
elem.addEventListener("click", function(e){
if (subject.hasIt(result[0]) == -1) {
subject.attach(new Observer(result[0]));
elem.innerHTML = "Unsubscribe";
} else {
subject.detach(result[0]);
elem.innerHTML = "Subscribe";
}
})
})
var notify = document.getElementById("notify");
notify.addEventListener("click", function(e) {
subject.notify();
})
}
</script>
</head>
<body>
<table>
<tr>
<td id=cella0></td>
<td id=cella1></td>
<td id=cella2></td>
</tr>
</table>
<button id=gomb0>Subscribe</button>
<button id=gomb1>Subscribe</button>
<button id=gomb2>Subscribe</button>
<button id=notify>Notify</button>
</body>
</html>
|
Comments (0)
You can clone a snippet to your computer for local editing. Learn more.