0

I've got a problem near that one. Somewhere I've got a binding over a file input :

var file;

function initLoadImg(){
    $('#test').on('change', function() {
        file = event.target.files;
        // block 1
        console.log("hello");
        center.html('<span id="Tamb">25°C</span>');
        over = true;
    });
}

And i'm triggering it with another javascript function :

var over = false;
var center;
function loadImg(){
    var elem = $('<div class="widget simpleimgchart center"><div class="matable"><div class="center"></div></div></div>');
    center = elem.children().children();
    $("#test").trigger('click'); 
    passIfOver();
    // block 2
    console.log("bye");
    return elem;
}

function passIfOver() {
    if (over) {
         return;
    } else {
         setTimeout(passIfOver(), 1000);
    }
}

This way, I'm able to see the "hello" before the "bye" in the console. However I don't really like this solution, (it's not clean) and user can have to wait up to 1s before getting any feedback. Would there be another way to ensure that the return elem is executed after the end of the callback on click?

edit : My code doesn't even work, because of the setTimeout, I lose the restraint...

edit 2 : My goal is to execute the part code 1 before the part code 2. I don't want my function loadImg() to return before the code 1 has finished to execute.

Community
  • 1
  • 1
Richard
  • 992
  • 1
  • 11
  • 27

2 Answers2

0

I recommend you to look at PubSub pattern (http://davidwalsh.name/pubsub-javascript).

Dmitry Volokh
  • 1,630
  • 16
  • 28
0

Just move the return inside the Trigger function:

var over = false;
function loadImg(){
    var elem = $('<div class="widget simpleimgchart center"><div class="matable"><div class="center"></div></div></div>');
    var center = elem.children().children();
    $("#test").trigger('click', function(){
        center.html('<span id="Tamb">25°C</span>');

        return elem;
    });  
}

The second argument to .trigger is a callback function everything inside it will be executed After the trigger is completed.

d.raev
  • 9,216
  • 8
  • 58
  • 79
  • The context is different. I don't need the callback to return elem but loadImg() to do so. Additionally loadImg() would be over before the end of the callback. – Richard Jul 28 '14 at 09:29