Zum Inhalt springen

Websiteentwicklung: JavaScript: Entwurfsmuster

Aus Wikibooks

Observer

[Bearbeiten]

Implementierung

[Bearbeiten]
<html><head><script type="text/javascript">
function Subject () {
	this.observers = new Array();
	this.register_observer = function(observer){
		this.observers.push(observer);
	}
	this.remove_observer = function(observer){
		for(var i=0; i < this.observers.length; i++){
			if(this.observers[i] === observer){
				this.observers.splice(i, 1);
			}
		}
	}
    this.set_value = function(value){
        this.value = value
        this.inform_observers()
    }
    this.inform_observers  = function(){
        for each (var observer in this.observers){
            observer.update(this.value)
    	}
    }
}
 
function Observer1 (subject){
    subject.register_observer(this);
    this.update = function(value){
        document.write("I'm observer 1 and subject value is "+value+"<br>\n");
    }
} 
 
function Observer2 (subject){
    subject.register_observer(this);
    this.update = function(value){
    	document.write("I'm observer 2 and subject value is "+value+"<br>\n");
    }
}
</script>
</head>
<body>
<script type="text/javascript">
var subject = new Subject();
var observer1 = new Observer1(subject);
var observer2 = new Observer2(subject);
subject.set_value(1);
subject.remove_observer(observer1);
subject.set_value(3);
</script></body></html>