I have created a simple javascript class using the ‘function’ technique.
In the class I have a websocket listener which triggers a function when a certain message is received.
I could easily add an external callback to it, as follows
function MyClass() {
self = this; // to access main object from methods
// websocket definition
function websocketMessageInterpreter(message){
if(message == "Hello!") onHelloMessageBase();
}
function onHelloMessageBase(param){
// call user defined callback
self.userDefinedCallback(param);
}
this.userDefinedCallback= function(param){}; //default empty callback
}
Externally I use this as
var myObject = new MyClass();
myObject.userDefinedCallback = function(){alert("Someone said hello!");};
Is there a model where I could do something like this?
myObject.userDefinedCallback += function1;
myObject.userDefinedCallback += function2;
and maybe later
myObject.userDefinedCallback -= function1;
The usual way to do this is to have an array of callbacks, and methods like
addCallback(callback)andremoveCallback(callback)to let users of the API add and remove callbacks.addCallbackis basically:removeCallbackis basically:If you need to support really old browsers like IE6 which may not have
Array#indexOf, since you’re using jQuery, you can usejQuery.inArrayinstead.