Search code examples
javascriptjqueryajax-upload

A race condition between new window object and link click


I'm encountering a race condition between a new window object creation and a link click. The new window is an plugin called AjaxUpload, whose input requires a link element with unique ID. Note that AjaxUpload brings up a new window of file selection.

The page requires many links that bring file selection windows with unique IDs. Therefore to simplify the scenario, the plan is to attach a new ID to a clicked link, create the window object, simulate a mouse click to bring up the window, destroy the ID, and do the same thing with other link.

However the problem occurs when the simulated click is executed before the window object is finished loaded resulting the code only works when the link is clicked twice.

Here is the code:

$(document).ready(function() {
            // The link is an anchor element with icon camera class
            // that will be attached with a new ID called wall-image-upload
            // which will destroyed after the window is brought up
            $( "a.icon.camera" ).click(function(e) {
                // Exit the function when wall-image-upload
                // id is created to avoid infinite loop
                if ($('#wall-image-upload').length!==0) {
                    return;
                }
                // Create the ID
                e.target.setAttribute("id", "wall-image-upload");

                // Create AjaxUpload object to handle the
                // image attachment where it looks up link 
                // with wall-image-upload ID
                var uploader = new window.AjaxUpload(
                   'wall-image-upload',
                   { action: 'wall_upload/{{$nickname}}',
                       name: 'userfile',
                       onSubmit: function(file,ext) { $('#profile-rotator').show(); },
                       onComplete: function(file,response) {
                           addeditortext(response);
                           $('#profile-rotator').hide();
                       }                 
                   }
                );
             // Simulate click on the element, this doesn't effect on
             // anything unfortunately
             $('#wall-image-upload').trigger("click");

             // Destroy the id
             $('#wall-image-upload').prop("id",null);

            }); 
});

where and how should I put

$('#wall-image-upload').trigger("click");

To be executed properly?


Solution

  • The question is irrelevant. There is no race condition occurred. The problem was, the simulated click doesn't bring up the window whatever the reason is. This question is closed.