0

I am using Websocket (javascript) which has the following events:

    ctrlScope.conn.onerror = function() {
      ctrlScope.updateStatus();
    };

    ctrlScope.conn.onclose = function() {
      ctrlScope.updateStatus();
    };

    ctrlScope.conn.onopen = function() {
      ctrlScope.updateStatus();
    };

As you can see I am updathing the chat status using those events, but it looks repetative, is there any way to combine all those Websocket events in one?

ctrlScope.conn[onError][onClose][onOpen] = function() {
   ctrlScope.updateStatus();
};

Additionally there is a Websocket variable: readyState which provides the status of the connection same as the events. This could replace the functions hassle, but $watch does not work on it.

Please some one help :(

1 Answer 1

1

I haven't tried this code, but in theory you could write it like this:

var handlers = ["onerror","onclose","onopen"];
for(var i=0;i<handlers.length;i++){
    ctrlScope.conn.[handlers[i]] = ctrlScope.updateStatus;
};

This is taking advantage of the javascript ability to refer to elements using either dot notation (ctrlScope.conn.onopen) or by array notation (ctrlScope.conn["onopen"])

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

Comments

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.