lundi 1 décembre 2014

Software Design - Interaction between two classes


First off, I am sorry if there is a trivial answer to this question but I am unable to find one.


The concept that I have in question is the following. I have a client app and a server app that exchange data. I am trying to separate the logic that handles a server update in the client in the following way.


A "main" class that handles application logic and works with parsed and sanitized data and a "worker" class that parses the received data and calls the appropriate method of the "main" class. I guess this is in some way imitating events. Here is an example structure to make things more clear.



var Main = function(){
this.init();
};

Main.prototype = {

init: function(){
//Do init logic

},

connect: function(){
var client = new Client();
client.onStateUpdate(this.executeStateUpdate);
client.connect('localhost', 3001);
},

executeStateUpdate: function(data){
// Problem - the "this" operator is now Client and not Main
}

};


var Client = function(){
};

Client.prototype = {
connect: function(host, port){
this.client = new WebSocket("ws://"+host+":"+port);

this.client.onmessage = function(e){
var data = JSON.parse(e);
//handle received data
stateUpdate(data);
};
},

stateUpdate: function(data){
//sanitize data to application objects
this.stateUpdateCallback(sanitizedData);
},

onStateUpdate: function(callback){
this.stateUpdateCallback = callback;
}
}


The biggest problem here is that calling "main" methods from the "worker" makes them point to the wrong object(e.g "Client" and not "Main"). I have thought about passing the "Main" class object to the "Client" object instead of callbacks, but this way I have to hardcode all the callback methods that would be called on each event that arises from the server. I am open to any suggestions on how to solve this matter and sticking to this architecture of the code is not mandatory for me.





Aucun commentaire:

Enregistrer un commentaire