Tim
Tim

Reputation: 13258

RequireJS: Define a module - TypeError: Unable to get property of undefined or null reference

I have two JavaScript files file1.js and file2.js which I want to create modules out of it to use it with RequireJS.

file1.js

define('file1', ['file2'], function(myVar) {
    console.log(myVar);

    myVar.doSomething = function() {
        return {
            'test': 13
        }
    }
});

As you can see, there is a dependency to file2.js and I need to get the myVar. Here you can see file2 and a code snippet what I am doing inside this file.

file2.js

define('file2', ['someOtherDep'], function(someVarFromSomeOtherDep) {
    var myVar = (function() {
        var test = someVarFromSomeOtherDep.test.a;

        var doIt = function(var1) {
            // …
            return x;
        };

        return {
            doIt: doIt
        }
    }());
    console.log(myVar);
    return myVar;
});

If I use file1 as a dependency and call myVar.doSomething(), I get TypeError: Unable to get property 'doSomething' of undefined or null reference and both console.log shows [object Object] {}.

Here is the file which depends on file1:

define(['file1'], function(myVar) {
    var test = myVar.doSomething();
});

So, what's wrong here? It seems that myVar is not returned correctly from file2?

Upvotes: 0

Views: 1539

Answers (1)

Bergi
Bergi

Reputation: 665344

both console.log shows [object Object] {}

That's odd. Have you tried expanding the view? You should be able to see your methods.

I get TypeError: Unable to get property 'doSomething' of undefined or null reference So, what's wrong here? It seems that myVar is not returned correctly from file2?

No. myVar is not returned correctly from file1 - in fact, nothing is returned there at all!

define('file1', ['file2'], function(myVar) {
    console.log(myVar);

    myVar.doSomething = function() {
        return {
            'test': 13
        }
    }
    return myVar;
//  ^^^^^^^^^^^^^
});

You're getting the error from the line var test = myVar.doSomething(); (that depends on file 1), not from file 1 (that depends on file 2).

Upvotes: 1

Related Questions