0

I have a function that is calling a jquery plugin function by first loading the plugin with RequireJS the problem is the plugin function inside requirejs only gets executed after my function already returned so hasMessageParent always returns null. I'm really confused because this was working fine before and I don't know what change and broke. How can I fix so myMsg gets set to the function return before continuing?

hasMessageParent: function() {
    var myMsg = null;
    var ctrl = '#myDiv';
    require(["my_msgcheck"], function() {
        // this gets executed after the return already happened, it returns true
        myMsg = $(ctrl).msg_check('hasMessage');
    });
    // this always returns null because the require jquery plugin function is executed after the return already happened
    return myMsg ;
},
user391986
  • 29,536
  • 39
  • 126
  • 205

1 Answers1

1

You can't fix this by modifying the function alone, you have to add "my_msgcheck" to the define call of your module.

Another option is to use a callback if your really only want to load it inside that function. But this could be a sign of a bad code structure.

var hasMessageParent = function(callback) {
    var myMsg = null;
    var ctrl = '#myDiv';
    require(["my_msgcheck"], function() {
        // this gets executed after the return already happened, it returns true
        myMsg = $(ctrl).msg_check('hasMessage');
        callback(myMsg);
    });
};
hasMessageParent(function (msg) {
    // ...
});
jgillich
  • 71,459
  • 6
  • 57
  • 85
  • wow clever thank you! the call back works however i don't understand the first way to fix it you mentioned, adding define call to which module? – user391986 Apr 18 '13 at 17:23
  • @user391986 What I meant is that the require call must happen before the function is called if you want to return `myMsg` directly. But the requirejs-way would be to define your code as modules: http://requirejs.org/docs/api.html#define – jgillich Apr 18 '13 at 17:27