0

I want to call this function, pass which type of error it is as an arg, and then display the message.

function msgDialog(msg) {
    // Define messages
    var errorMsg = "There has been an error.  We are sorry about that.";
    var loginMsg = "Something went awry with the login.  Please try again.";
    var uploadMsg = "Your upload failed.  Please try again.";
    var networkMsg = "You currently are not connected to the internet.  Please connect and try again.";
     alert(msg);
}

How do I call that function msgDialog(loginMsg) and have a var which I can assign to the correct message, then do something with that? Here I am alerting it, but I will really display it differently. I know that I need to create a new var with the value of the arg value, but not sure how. Thank you.

B-Money
  • 1,040
  • 10
  • 12
  • I'm not sure I understand your question. Can you try to explain another way? – Ray Nicholus Apr 09 '13 at 02:09
  • Yeah. I want to call that function and I want to display a message depending on the argument sent. For instance, if I called msgDialog(loginMsg), I want the alert to display "Something went ...", not just the arg var name. – B-Money Apr 09 '13 at 02:13

1 Answers1

4

That is pure JavaScript, no jQuery. Try this:

var msgDialog = (function() {
    var errors = {
        errorMsg : "There has been an error.  We are sorry about that.",
        loginMsg : "Something went awry with the login.  Please try again.",
        uploadMsg : "Your upload failed.  Please try again.",
        networkMsg : "You currently are not connected to the internet.  Please connect and try again."
    }

    return function(msg){
        alert(errors[msg]);
    }
})();

msgDialog('uploadMsg'); //  alerts "Your upload failed.  Please try again."

You can get an idea of what's going on here if you hadn't seen JavaScript closures before.

Community
  • 1
  • 1
Nicolas
  • 2,297
  • 3
  • 28
  • 40
  • way cooler than what i would have said :). can you post a usage statement? – Doug Apr 09 '13 at 02:22
  • OK yeah cool thanks. And how do I call that var function? For instance, I have other events going on, and on a failure of an event I want to call that msgDialog function from multiple other callbacks. – B-Money Apr 09 '13 at 02:38
  • You can see a usage example in the last line of the code. Call it as every other function, passing the name of the message you want to display as a string. – Nicolas Apr 09 '13 at 02:39
  • Rocking good Nicolas. Thank you. Very clean and tight. I bow down to your js kungfu, empty my cup and offer you a delicious beverage of your choice. – B-Money Apr 09 '13 at 02:54
  • You're welcome. For more abstraction you can remove the "Msg" part from all the message names; they are redundant. I mean calling msgDialog('error') instead of msgDialog("errorMsg"). – Nicolas Apr 09 '13 at 02:56