To class or not to class, that has been a question than many developers have faced as they came from class based OO worlds into the Prototype Oriented world of JavaScript. Much pain has endured for those that try to contort it.
Peter Michaux has detailed transitioning from Java Classes to JavaScript prototypes by looking at the Observer/Observable pattern and showing various implementations in Java and JavaScript ending up with his favourite mixin-able solution:
-
-
var observablize;
-
-
(function() {
-
-
var observable = {
-
-
addObserver: function(observer) {
-
if (!this.observers) {
-
this.observers = [];
-
}
-
this.observers.push(observer);
-
},
-
-
notifyObservers: function() {
-
for (var i=0; i<this.observers.length; i++) {
-
this.observers[i].update();
-
}
-
}
-
-
};
-
-
observablize = function (subject) {
-
for (var p in observable) {
-
subject[p] = observable[p];
-
}
-
}
-
-
})();
-
-
// ---------------------------
-
-
function WeatherModel() {}
-
-
observablize(WeatherModel.prototype);
-
-
WeatherModel.prototype.setTemperature = function(temp) {
-
this.temp = temp;
-
this.notifyObservers();
-
};
-
-
WeatherModel.prototype.getTemperature = function() {
-
return this.temp;
-
};
-
-
// ---------------------------
-
-
function CurrentConditionsView(model) {
-
this.model = model;
-
model.addObserver(this);
-
}
-
-
CurrentConditionsView.prototype.update = function() {
-
alert(this.model.getTemperature());
-
};
-
-
// ---------------------------
-
-
var victoriaWeather = new WeatherModel();
-
var victoriaNews = new CurrentConditionsView(victoriaWeather);
-
-
victoriaWeather.setTemperature(15.3);
-
victoriaWeather.setTemperature(17.0);
-
victoriaWeather.setTemperature(14.7);
-



