What is the process for including "onload" in my Dojo class?

Is there a way for me to incorporate an "onload" function into my personalized Dojo class which can trigger functions that are registered to listen for the event? Perhaps something like myWidget.addOnLoad(...)

My class doesn't belong to Dijit, it's a basic class that uses dojo.declare. When instantiated, various functions (xhr, etc) are called to set up the class and I wish to have the capability to inform other JavaScript functions that the widget has been loaded and is ready.

Answer №1

Have you thought about utilizing the dojo.publish() method to emit a message when the widget is fully prepared? Alternatively, if the other part of the code can access the widget, you could create an empty function within the widget called "loaded" and then the other code could establish a connection using dojo.connect to be notified when this "loaded" function is triggered.

Answer №2

According to the findings of jburke, Dojo simplifies the process for you: all you need is dojo.connect. Here's a demonstration:

x = {
    loaded: function() { console.log('[x] loaded'); }
}
y = {
    dependentAction: function() { console.log('[y] dependentAction'); }
}
dojo.connect( x, 'loaded', y, 'dependentAction' );
x.loaded()
// displays:
// [x] loaded
// [y] dependentAction

Simply call x.loaded() after completing the loading of x.

Answer №3

After studying the Dojo addOnLoad functions, I decided to incorporate them into my class. To me, this approach seemed to be the most effective and straightforward. While considering using a pub/sub or dojo.connect method, I believe that this implementation stands out as the cleanest and most intuitive solution.

Here are the key components that I extracted from dojo.js and integrated into my class:

_addToQueue : function(array, object, functionToAdd){
    if(!functionToAdd){
        array.push(object);
    }else if(functionToAdd){
        var callback = (typeof functionToAdd == "string") ? object[functionToAdd] : functionToAdd;
        array.push(function(){ callback.call(object); });
    }
},

_loadComplete : function() {
    this._notifyLoading = true;
    this._afterLoad = true;
    var loadersList = this._loaders;
    for(var i = 0; i < loadersList.length; i++){
        try{
            loadersList[i]();
        }catch(error){
            throw error;
            console.error("addOnLoad callback failed: " + error, error); /* continue with other load events, like the parser, but report the error */
        }
    }
    this._notifyLoading = false;
    //Ensure that no additional callbacks were added to the onload queue
    //after the initial run. If any were added and there are no more waiting resources,
    //rerun the function.
    if(this._afterLoad && this._pendingResources == 0 && loadersList.length){
        this._loadComplete();
    }
},

addOnLoad : function(/*Object?*/object, /*String|Function?*/functionName){
    this._addToQueue(this._loaders, object, functionName);   
    if(this._afterLoad && !this._notifyLoading){
        this._loadComplete();
    }
}

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

anychart: The right side of Gantt Charts is being cut off or trimmed

I am utilizing anychart for my user interface. My data timelines are in epoch milliseconds. When trying to create a Gantt chart, I notice that the right side is being trimmed. Can someone please assist me with this issue? https://i.sstatic.net/H6LHk.png ...

Storing data values from a specific object key into an array in Vue: Step-by-step guide

Just dipping my toes into the world of Vue framework here. I managed to create a selectable table that stores data in an object. I want this function to run in the background, so I figured it should be in the computed section. The object structure is as fo ...

I'd like to know how to retrieve the start and end dates of a specific month using JavaScript

How can I retrieve the start and end date of the current month? const currentDate = new Date(); const startOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1); const endOfMonth = new Date(currentDate.getFullYear(), currentD ...

Issue regarding Jquery widget

I am working with a widget that looks like this $.widget("ui.myWidget", { //default options options: { myOptions: "test" }, _create: function () { this.self = $(this.element[0]); this.self.find("thead th").click(fun ...

Creating an original list by iterating through a given list

I understand that some may consider this a duplicate, but I have yet to come across a similar example that I can relate to with my limited knowledge. So, I apologize in advance :) This should be pretty simple for an experienced JS developer, I assume. My ...

In production, all Next.js API routes consistently return an "Interval Server Error," whereas in development, all routes operate smoothly without any issues

Every time I access any API route in my Next.js application in production, it results in a 500 "Internal Server Error". However, in development mode, all routes function smoothly and provide the expected output. https://i.stack.imgur.com/nPpeV.png https: ...

How to use OBJLoader/Three.js to load a specific URL in JavaScript

I am encountering an issue with a JavaScript code snippet from the three.js OBJloader. I should mention that my experience level in JS and PHP is limited as I am just starting out with WordPress websites. My problem lies in utilizing the setPath and load ...

Tips for converting a "callback pyramid" into a promise-based structure

I'm currently struggling with understanding how to refactor my code to use promises or the Q library effectively. Let's consider a common basic example: I have a test case that imports the same file twice into a MongoDB database and then checks ...

The website is missing the display of Google Maps

The Google map is not displaying on my website page that uses PHP. I need assistance with this issue. Below is the webpage URL and the source code: <section class="meteor-google-map fullwidth block" style="height: 450px; border: solid transparent; bo ...

Angular-powered SPAs with cookie authentication

My current web framework utilizes cookie (or token) based authentication. Upon user registration, a postback occurs and the server embeds an authentication token into a cookie which is then linked to the user's browser. Subsequent requests utilize thi ...

Error in Node.js Express: Attempted to access property 'image' of null resulting in an unhandled error event

I've been trying to identify where the issue lies. Can someone lend a hand with this? When attempting to submit the post without an image, instead of receiving a flash message, the following error pops up: and here's the source code link: https: ...

What is the method for setting autofocus to the first input element within a loop?

I am currently working on a loop to display inputs, and I would like to be able to add focus to the first input element when it is clicked. Does anyone have any suggestions on how I can select that first element and set autofocus on it? ...

Mapping various sets of latitudes and longitudes on Google Maps

I am working with multiple latitude and longitude coordinates. var latlngs = [ {lat:25.774252,lng:-80.190262}, {lat:18.466465,lng:-66.118292}, {lat:32.321384,lng:-64.757370}, {lat:25.774252,lng:-80.190262}, ]; The coordinates were ret ...

Issues have arisen with Google Maps functionality following the API integration, resulting in a blank grey

I am experiencing an issue with Google Maps where it is displaying a grey box or sometimes showing nothing/white. I have tried various solutions found online but none of them have worked for me. Does anyone have a solution? I even attempted to change the ...

How can I implement Jquery validation engine ajax for two different fields using the same function?

The jQuery validation engine plugin has a unique feature of performing ajax validation. However, there is a minor inconvenience with this functionality. Instead of validating the field name, it sends the field ID for validation. Why does this pose a prob ...

Leverage the Redux store as the source of data for sending a POST request

For my React project, I designed an input interface and saved the data in a Redux state. Afterward, I set up a new action for making an API call to post the data. When using a constant value as the "data" parameter, everything functions properly. However ...

Unable to display numerous bars on the x-axis in vue-chartjs

Having trouble displaying a stacked bar chart with two bars sharing a label on the x-axis. The issue is that the 2nd bar sits below the first one (if you hide the 2021 value, the 2022 bar will appear): var barChartData = { labels: ["January", "Febru ...

Using JSON with a jQuery AJAX function

Hello everyone! I'm relatively new to the world of AJAX and I'm having trouble figuring out what's wrong with my code. I'm creating a form that should display content from a database using autocomplete. I'm attempting to update a ...

Troubleshooting issue with Django forms and JavaScript interactions

For the past day, I've been grappling with a particular issue and haven't made much progress. My setup involves using a django inline form-set, which displays all previously saved forms along with an additional empty form. To show or hide these f ...

Can the parcel bundler dist folder be customized for decoration?

After compiling code with parcel using the command parcel src/index.html, all files are generated inside the dist folder. However, I am looking for a more organized way to manage these files once my website is complete. Ideally, I want separate folders suc ...