-1

I want to make a .on function but I'm having a problem. The below code calls the .on function but to do the alert, the variable ready has to be true. I don't want to call the .on function after the "ready = true". I hope you understand me. Thanks.

var test = {};
var ready = false;
test.on = function(argument, callback) {
    if (typeof argument !== "string" || "function" !== typeof callback) return;
    if (typeof callback === "function") {
        if (argument === "hi" && ready) {
            callback("hi");
        }
    }
}
test.on("hi", function(a) {
    alert(a);
});
ready = true; // Now it should evaluate the above function
xF4B
  • 76
  • 9
  • 1
    so you want to evaluate your function when ready is changed? – Edwin Jun 23 '17 at 12:34
  • yes, when i change ready to true, as the function has already been called it should be evaluated – xF4B Jun 23 '17 at 12:36
  • well something needs to watch for the ready variable to change.... and you are going to have to queue up the calls until that state happens. – epascarello Jun 23 '17 at 12:37
  • then you need to create a listener to your variable and when changed call your function. Something like https://stackoverflow.com/questions/1759987/listening-for-variable-changes-in-javascript-or-jquery – Edwin Jun 23 '17 at 12:40

1 Answers1

0

To make the alert be called before calling ready = true you'll need to change the boolean login of the test.on function.

If you remove the && ready

test.on = function(argument, callback) {
    if (typeof argument !== "string" || "function" !== typeof callback) return;
    if (typeof callback === "function") {
        if (argument === "hi") {
            callback("hi");
        }
    }
}

Then when you call test.on(hi.. it'll now show the alert.

Tom
  • 2,315
  • 1
  • 14
  • 21
  • Technically this is correct, however the comments now show the question was about something totally different. – Tom Jun 23 '17 at 12:38
  • No you haven't understood me. I want to make it with the variable – xF4B Jun 23 '17 at 12:39