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 ;
},

1 Answer 1

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) {
    // ...
});
Sign up to request clarification or add additional context in comments.

2 Comments

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 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: requirejs.org/docs/api.html#define

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.