The code will be more or less complex, depending on your requirements that are not clear. Don't use a pattern if you don't need it, and a pattern can be adjusted in many ways depending on your requirements. Don't try to build the all-for-all solution if you don't realy need it.
If you have many observers and know them at creation time of the car, you can use
function Car(onGearChangedArray) {
this.triggerGearChanged = function() {
for (var i=0;i<onGearChangedArray.length;i++) {
onGearChangedArray[i]();
}
};
window.setTimeout(this.triggerGearChanged,2000);
}
var car = new Car([function(){
console.log("gear changed");
}]);
If you only have exactly one observer, you can get rid of the for loop.
But if you need the flexibility to add them at runtime:
function Car() {
var onGearChangedCallbacks = [];
this.onGearChanged = function(callback) {
onGearChangedCallbacks.push(callback);
};
this.triggerGearChanged = function() {
for (var i=0;i<onGearChangedCallbacks.length;i++) {
onGearChangedCallbacks[i]();
}
};
window.setTimeout(this.triggerGearChanged,2000);
}
var car = new Car();
car.onGearChanged(function(){
console.log("gear changed");
});
Or if you want to abstract it the next level
function Event() {
var callbacks = [];
this.bind = function(callback) {
callbacks.push(callback);
};
this.fire = function() {
for (var i=0;i<callbacks.length;i++) {
callbacks[i]();
}
};
}
function Car() {
this.gearChanged = new Event();
window.setTimeout(this.gearChanged.fire,2000);
}
var car = new Car();
car.gearChanged.bind(function(){
console.log("gear changed");
});
Thanks for the abstraction idea to Khanh TO, I just wanted to show it without parameters.
You could also consider using something more sophisticated, so that you don't need to write this event handling code yourself (like error handling etc.), but again, it depends on your needs. Do you need a fail fast strategy, or should errors be just logged? Must Listeners be unregistered? Could you trap yourself in an infinite loop because triggerGearChanged could lead to another triggerGearChanged? Do you need to pass parameters or not? Keep in mind to keep it as simple as possible, so if you don't need to pass parameters, then don't do it.
If you like unserscore.js, a good start may be http://mattmueller.me/blog/underscore-extension-observer-pattern
Car.