2

I have two modules within the same namespace, and I want to pass a variable between them. The namespace is called app, and the variable is a - but for some reason my variable a always comes out null when my method is called.

Here is the code:

// module 1
(function() {
    app.module1 = (function() {
        var a = null; 
        canvas.addEventListener('mousedown', function(e) {
            a = { message: hallo };
            app.module2.print();
        }, 0);

        return {
            a: a
        };
    })();
})();

// module 2

(function() {
    app.module2 = (function() {
        var print = function() {
            console.log(app.module1.a);
        }

        return {
            print: print
        };
    })();
})();
1
  • Did you mean to have a = { message: "hallo" };? Where hallo becomes a string? Or is that defined somewhere off the screen? Commented May 3, 2013 at 23:49

2 Answers 2

1

Check this jsbin

Basically what you can do is to calculate variable each time:

In your module 1:

a: function(){return a;}

Wherever you are using a:

console.log(app.module1.a());
Sign up to request clarification or add additional context in comments.

1 Comment

console prints ERROR: a is not a function
1

It's because your handler is referring to the local a and not the a property on the module. I suggest you modify the object instead, or you could do this:

// module 1
(function () {
  app.module1 = (function () {
    var interface = {
      a: null
    };
    canvas.addEventListener('mousedown', function (e) {
      //this way, you are modifying the object
      interface.a = {
        message: hallo
      };
      app.module2.print();
    }, 0);
    return interface;
  })();
})();

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.