JavaScript module pattern and the use of global variables

It seems like a pretty straightforward task, but I'm struggling to make it work:

// This is just for demonstration purposes, how can I access the canvas from within the rotate method?
_imagePreview = function()
{
    var canvas = '';

    return {

        load: function() {

            fileReader.onload = function(e) {

                image = new Image();

                image.onload = function() {

                    // The value should be an empty string here
                    console.log(this.canvas);

                    canvas = $('#myCanvas')[0];

                    // Now, this should log the Canvas object
                    console.log(this.canvas);

                    return true;
                }
                
            }

           image.src = e.target.result;            
        }

        fileReader.readAsDataURL(file);
    },

    rotate: function() {

        // At this point, the value of canvas is undefined which is not what I expected
        console.log(canvas);
    }
}

I am invoking _imagePreview.load() first, followed by _imagePreview.rotate(), however, I am not able to retrieve the correct value for canvas.

The rotate method gets triggered by a click event after the user selects a file and it gets rendered into the canvas. Hence, rotate will always execute after load. Here's an example:

$("#rotate-clockwise").click(function() {

    _imagePreview().rotate('+', 90);
});

$("#rotate-counter-clockwise").click(function() {

    _imagePreview().rotate('-', 90);
}); 

Answer №1

The main issue lies in the fact that _imagePreview() is being called multiple times. With each call, a new set of functions for load and rotate, along with their own canvas variable, are created.

To resolve this, make sure to call _imagePreview only once, save the result, and then utilize that object to invoke the load and rotate functions when needed.

Answer №2

To start, begin by defining private variables and then proceed to create an object containing functions that utilize these private variables.

_imagePreview = function() {
    var canvas = 'I am a canvas!';

    return {
        load: function() {
            canvas = 'I am a loaded canvas!';
        },
        rotate: function() {
            console.log(canvas);
        }
    };
}

_imagePreview().rotate();
// Output: I am a canvas!

var preview = _imagePreview();
preview.load();
preview.rotate()
// Output: I am a loaded canvas!

Answer №3

This JavaScript code is incorrect. Expect to encounter errors soon. The object being returned should have an additional set of curly braces enclosing it.

return {
    initialize: function() {
        // ...
    },
    execute: function() {
        // ...
    }
};

If you wish to call the execute function from within initialize using a similar method, you could try:

var _execute = function() {
    // ... perform execution
};

var _initialize = function() {
    _execute();
   // ... do some other tasks ...
};

return {
    initialize: _initialize,
    execute: _execute
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why does the Leaflet map appear inconsistently?

It's baffling that Firefox 24.0 and the latest Chrome are both failing to load my Leaflet map, but surprisingly, it works perfectly on Safari on my iPhone. Quite an interesting dilemma. This is my initial attempt at using Leaflet and Bootstrap...ever ...

Troubleshooting a VueJS Problem: Updating $data in the mounted hook

Revision This snippet of Component.vue was extracted from a larger web application where I made a mistake that had significant consequences, all because of a small change I didn't initially notice. An important distinction exists between the followi ...

Utilizing AngularJS, combining ng-repeat and filter functions that can be triggered directly from the controller

I have a burning question to ask. Here's the HTML code snippet: ng-repeat="item in obj.Items | filter:someFilter" And here's the JS code snippet: $scope.someFilter = function (item) { ... } It all works perfectly fine. However, I am faced wi ...

What could be causing the lack of response from PHP Ajax?

In the midst of tackling my college project, I find myself working on a webpage that is designed to showcase City and temperature information. To accomplish this task, I am delving into the realm of AJAX in order to dynamically update the temperature at sp ...

Can someone clarify the meaning of (e) in Javascript/jQuery code?

Recently, I've been delving into the world of JavaScript and jQuery to master the art of creating functions. I've noticed that many functions include an (e) in brackets. Allow me to demonstrate with an example: $(this).click(function(e) { // ...

What is the best way to retrieve the href and id values dynamically from a card in React JS?

Hello everyone, I'm new to stackoverflow and still in the process of learning how to code. Please bear with me if this question sounds like a newbie one. My question is about having dynamic values for href and id when mapping data using axios to crea ...

Is it possible to continuously re-render a React Functional Component with Axios and useState/useEffect?

Seeking assistance with creating a React Functional Component using Typescript to fetch data from an API and pass it to another component. However, encountering the error message "Error: Too many re-renders. React limits the number of renders to prevent an ...

How can I transfer a PHP variable into a JavaScript variable nested within another PHP variable

After my php/html script generates the image, I am looking to display it without needing to reload the page. I currently call a javascript function within the PHP code to change the image. However, I am unsure how to pass the new image name to this javasc ...

Disrupting a Program Operation

We are utilizing the gauge Google Chart applet to visually track the failure rates of message transfers on a SOAP interface via AJAX. My goal is to make the page's background flash red and white when the failure rate reaches 50% or higher, and remain ...

Is there a permanent solution to fixing the error code -4094 that is repeatedly occurring during React Native startup?

When attempting to execute react-native start, an error occurred which has not been encountered before. The error message is as follows: ERROR ENCOUNTERED Loading dependency graph...events.js:287 throw er; // Unhandled 'error' event ...

Leveraging partials on their own

I am currently exploring the possibility of loading a partial in linkedin-dustjs without having to load its parent along with it. For instance, consider this partial (login.dust): {>layout/} {<content} <!-- Login Screen --> {/content} Th ...

I'm struggling to understand the reason why the input isn't being updated correctly with MobX

After attempting to implement MobX with React, I'm having trouble understanding why the input field's value is not updating. Below is the code I have created: @observer(['recipeStore']) class App extends Component { render() { r ...

Is the MongoDB Query construction functioning properly in Node.js?

Struggling to construct a MongoDB query using OR and AND logic, where each OR word between keywords is placed in the Should block, and each AND word between words is placed in the must block. example - keyword1 OR keyword2 => both should be in the s ...

Nodejs - how to achieve interoperability between mjs and js files through importing and requiring?

I'm fairly new to JavaScript and Node.js. Based on my research, it seems that ES6 import is not compatible with Node.js, so I've resorted to using experiment mode by renaming my file to .mjs. This workaround generally works, except when the .mjs ...

Applying background-image in ngStyle results in an undefined value

I have been attempting to incorporate images (retrieved through an API) as the background-image of an element. However, I keep encountering the error message Cannot read property 'url' of undefined, even though the URL is actually being rendered. ...

In which location can one find the compiled TypeScript files within an Angular 2 project?

As a newcomer to learning Angular 2, I've come across tutorials that mention all compiled files should go into the dist folder. These compiled files refer to typescript files transpiled into JavaScript. However, upon creating my project using Angular ...

adding the authentication token to the Dropzone configuration for headers

I am tasked with including the header access token. $scope.dropzoneConfig = { 'options': { // passed into the Dropzone constructor 'url': 'SOME API URL' + $scope.SOME_ID }, 'eventHandlers': { ...

One way to create a unique JavaScript Module Pattern that retrieves the default value of a

I'm struggling to retrieve the latest private property from a Module, as I keep getting the initial value instead of the most recent one. Upon submission of the form and triggering onSuccess, I assign partnerId = 10. Subsequently, upon clicking an e ...

Converting a Backbone collection with attributes into a JSON format

Can you provide guidance on serializing a Backbone collection with attributes and models into JSON? For example, consider the following collection: var myCollection = Backbone.Collection.extend({ initialize: function (attr, options) { this.prop ...

Is there any importance to port 9229 and is it possible to modify it?

In my initial training, it was always recommended to run a local Node server on port 3000. However, after learning about the Chrome Node debugger in a tutorial that uses port 9229, I decided to switch to this port. For more information on port 3000, you ...