возможная реализация
<html>
<head>
</head>
<body>
<div id="content_">start</div>
<script>
Publisher={
create: function(name, event){
var o=Object.create(this)
event.onEvent=function(){o.notyfy()}
o.event=event
o.subscribers=[]
window[name]=o
},
subscribe: function(subscriber, action){
this.subscribers.push(subscriber)
subscriber["on"+this.event.name]=action
},
unsubscribe: function(subscriber){
delete subscriber["on"+this.event.name]
this.subscribers=this.subscribers.filter(function(s){return s!=subscriber})
},
notyfy: function(){
var name=this.event.name
this.subscribers.forEach(function(s){s["on"+name]()})}
}
Event={
onEvent: function(){},
create: function(name, event){
var o=Object.create(this)
o.self=event
o.name=name
window[name]=o
},
activate: function(arg){this.self(arg); this.onEvent()}
}
/////// EXAMPLE ///////
Div={
create: function(name, text){
var o=Object.create(this)
o.self=document.createElement("div")
o.self.innerHTML=text
document.body.appendChild(o.self)
window[name]=o
}
}
send=function(){
var xhr=new XMLHttpRequest
xhr.open("GET", "http://localhost:8888")
xhr.onreadystatechange=function(){
if(xhr.readyState == 4) if(xhr.status==200) {rewriteContent.activate(xhr.responseText)}
}
xhr.send(null)
}
Div.create("fooDiv", "foo<br>")
Div.create("barDiv", "bar<br>")
Div.create("bazDiv", "baz<br>")
Event.create("rewriteContent", function(text){content_.innerHTML=text})
Publisher.create("rewriteContentListener", rewriteContent)
;(function(onrewriteContent){
with(rewriteContentListener){
subscribe(fooDiv, onrewriteContent)
subscribe(barDiv, onrewriteContent)
subscribe(bazDiv, onrewriteContent)
}
}
)
(function(){this.self.innerHTML+="response has received<br>"})
send()
send()
setTimeout(function(){rewriteContentListener.unsubscribe(fooDiv)}, 1000)
setTimeout(send, 3000)
</script>
</body>
</html>
////// OUT: ///////////
//response text from server
//foo
//response has received
//response has received
//bar
//response has received
//response has received
//response has received
//baz
//response has received
//response has received
//response has received