2

I want to write a program, that displays a rect, when the mouse clicks on the canvas element. I have certain modules, but somehow they seem not to be connected. I pasted the the code without a namespace in a JSFidlle:

fiddle

displaying module

(function(){
    display = (function(){
        var canvas = document.getElementById('canvas');
        var context = canvas.getContext('2d');
        return {            
            canvas: canvas,     
            context : context 
        }
    })();
})();

manager-module

(function(){
    manager = (function(){
        var canvas = display.canvas;    
        var context = display.context ;
        var rect = function(){
            ctx.fillRect(10,10,20,20);
        }
        return {
            rect: rect
        }
    })();
})();

main-module

(function(){
    canvas.addEventListener('mousedown', function(e) {
        manager.rect;
    }, 0);  
})();
0

2 Answers 2

2

You forgot to call the manager.rect function. Add some () in main-module and you'll be fine.

Essentially what you're doing in manager-module is this:

manager.rect = function () { ctx.fillRect(10, 10, 20, 20); };

Now when you access manager.rect, it'll return the value function () { ... }, because that's the content of the .rect property.
You need to add parentheses (), to tell the JS engine that it should call the function, not just retrieve it.

Sign up to request clarification or add additional context in comments.

2 Comments

@Reanimation thank you for the fast answer, it works, but why do I need the (), I thought the function is in variable rect as a function?
Because JavaScript uses () to call functions and property accesses are not function calls. I've edited in some small explanation.
0

They are all in their own anonymous function, so they are all in their own namespace. If you'd like each section to be able to communicate with each other put all the code in only one anonymous function.

2 Comments

They don't use the var keyword and will default to the global namespace. Ugly and unmaintainable, but it works.
New to me, you learn something everyday, will remove this answer soon then.

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.