8

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;
1
  • you could write nested functions into the callback Commented Jan 16, 2013 at 12:39

1 Answer 1

11

The usual way to do this is to have an array of callbacks, and methods like addCallback(callback) and removeCallback(callback) to let users of the API add and remove callbacks.

addCallback is basically:

function addCallback(callback) {
    if (this.callbacks.indexOf(callback) < 0) {
        this.callbacks.push(callback);
    }
}

removeCallback is basically:

function removeCallback(callback) {
    var index;
    if ((index = this.callbacks.indexOf(callback)) >= 0) {
        this.callbacks.splice(index, 1);
    }
}

If you need to support really old browsers like IE6 which may not have Array#indexOf, since you're using jQuery, you can use jQuery.inArray instead.

Sign up to request clarification or add additional context in comments.

5 Comments

Is toString() applied to the functions or how do you actually compare two functions, if they are the same?
@Amberlamps: It's a simply identity comparison, like for any other object.
@FelixKling: Okay, and that identity comparison also works for anonymous functions?
@Amberlamps: Yep... anonymous functions are just objects as well. It's totally independent from whether a function has a name or not.
Very interesting solution. I'm testing it and get back for the deserved acceptance

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.