Tuesday, August 21, 2012

Adding listener functions to a JavaScript object

I have the following code which defines a Car. Each Car has a color, along with a setColor(color) function. I want to add listener functions which are called whenever setColor(color) is called, and I want to be able to tack these listener functions on whenever I want. Is this a suitable approach? Is there a cleaner way?



function Car() {

this._color = \'red\';
this._callbacks = {};

this.setColor = function(color) {
this._color = color;
console.log(\">>> set car color to \" + color);
if (this._callbacks[\'setColor\']) {
this._callbacks[\'setColor\']();
}
};

this.addListener = function(functionName, handler) {
if (this._callbacks[functionName]) {
var oldCallback = this._callbacks[functionName];
this._callbacks[functionName] = function() {
oldCallback();
handler();
}
} else {
this._callbacks[functionName] = function() {
handler();
}
}
};


}

var car = new Car();
car.setColor(\'blue\');
car.addListener(\'setColor\', function() { console.log(\"This is listener # 1\"); });
car.setColor(\'green\');
car.addListener(\'setColor\', function() { console.log(\"This is listener # 2\"); });
car.setColor(\'orange\');


Output:



>>> setColor to blue
>>> setColor to green
This is listener # 1
>>> setColor to orange
This is listener # 1
This is listener # 2






Rating: 1 out of 5 based on 3 ratings



The post Adding listener functions to a JavaScript object appeared first on Javascript ASK.






via Javascript ASK http://javascriptask.phpfogapp.com/adding-listener-functions-to-a-javascript-object.html

No comments:

Post a Comment