Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I have a background script that is responsible for getting and setting data to a localStorage database. My content scripts must communicate with the background script to send and receive data.

Right now I send a JSON object that contains the command and the data to a function. So if I'm trying to add an object to the database I'll create JSON that has a command attribute that is addObject and another object that is the data. Once this is completed the background scripts sends a response back stating that it was successful.

Another use case of the function would be to ask for data in which case it would send an object back rather than a success/fail.

The code gets kind of hacky once I start trying to retrieve the returned object from the background script.

It seems like there is probably a simple design problem to follow here that I'm not familiar with. Some people have suggested future/promise design problems but I haven't found a very good example.

Content Script

function sendCommand(cmdJson){
chrome.extension.sendRequest(cmdJson, function(response){
    //figure out what to do with response
});
}

Background script

if (request.command == "addObject"){
  db[request.id]= JSON.stringify(request.data); 
    sendResponse("success");
}
else if(request.command == "getKeystroke"){
  var keystroke = db[request.id];
  sendResponse(keystroke);
}
share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

Well, I am not sure about which pattern you will call it. I would say following looks like Command pattern, I would do this..

var commands = {
         "addObject":function(request){/*Do something, send response etc*/},
         "getKeystroke":function(request){/*Do something, send response etc*/},
}

And in request handler

var requestHandler = function(request) {
      commands[request.command](request);
}
share|improve this answer
    
Yeah this is exactly what I ended up doing. –  ZeroDivide Feb 23 '12 at 15:40
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.