user1064499
user1064499

Reputation: 115

How can I call a nested function from outside its parent function?

I am working on an HTML file with JavaScript in it.

Here is the JavaScript code:

var dImage = new Image();

var drawing = (function () {

    .
    .
    .
    .

    redrawing = function () {
        context.drawImage(dImage, dX, dY, dWidth, dHeight);
    },

    init = function () {
        dImage.src = "images/d.png";
        redrawing();
    };

    return {
        init: init
    };

}());

function updateImage(dSrc){
    dImage.src = dSrc;
    // Call redrawing here
}

In the HTML I call

drawing.init();

and it is working fine. Also I can change the image source by calling

updateImage("images/d2.png");

and it is working for changing the source.

But I need to call redrawing() in the method updateImage() to refresh the image.

I try to call it in many ways (for example, drawing.redrawing();) but there is no response from redrawing().

Upvotes: 2

Views: 3014

Answers (2)

Paul D. Waite
Paul D. Waite

Reputation: 98826

If you want to be able to call the redrawing function from outside of the function it’s defined in, you need to return it from that function, just like you’ve done with init:

var drawing = (function () {

    .
    .
    .
    .

    return {
        init: init,
        redrawing: redrawing
    };
}());

Upvotes: 4

Waleed Khan
Waleed Khan

Reputation: 11467

Make redrawing public:

return {
    init: init,
    redrawing: redrawing
};

Upvotes: 1

Related Questions