0

I just started with require.js today. I was planning to create module and have sucessfully created one.

Now I want to make a recursive call to a return function in the module. How to do that?

My module.

define(['jquery', 'underscore'], function ($, _) {

    var thisModule = this;
    return {
        moduleFuntion: function (data) {
            //Code
            ...
            //How to call moduleFunction here.
        }
    }

});

I have tried

modelFunction();

and

thisModule.moduleFuntion();

I think splitting the code into another function rather than the return function and caling that recursively works

define(['jquery', 'underscore'], function ($, _) {

    var thisModule = this;
    function codeFunction(data) {
      //Code
      ....
      codeFunction()
    }
    return {
        moduleFuntion: function (data) {
            codeFunction(data);
        }
    }

});

But instead of that is that possible in my current code?

Update :

I have solved issue by

define(['jquery', 'underscore'], function ($, _) {

    return {
        moduleFuntion: function (data) {
            //Code
            ...
            var moduleObject = require('jsonviewer');
            moduleObject.moduleFuntion(dataNew);
        }
    }

});

Is this this the correct approach?

Note: I'm new to require so I would like to get experts opinion on the path I took

2 Answers 2

1

Actually,

this.moduleFuntion();

should do the trick.

var thisModule = this;

Doesn't work since you are assigning the variable outside of the object you are returning, and thereby this isn't pointing to the object.

Here is a very simple example: http://jsfiddle.net/ePV2Q/

Sign up to request clarification or add additional context in comments.

2 Comments

As I mentioned in the question I have tried that thisModule.moduleFuntion();' where var thisModule = this;`
Since you are assigning the thisModule variable outside of your object, it doesn't point to the object scope, but to the scope your module is in.
0

I'd reccomend reading up on named function expressions.

define(['jquery', 'underscore'], function ($, _) {

    var thisModule = this;
    return {
        moduleFuntion: function moduleFunc(data) { // give this function expression a name
            //Code
            ...
            //How to call moduleFunction here.
                // Now you can call moduleFunction using moduleFunc:
                moduleFunc(...);
        }
    }

});

Comments

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.