Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

requirejs, two classes in one file

I just started out with RequireJS, but i'm stuck at the part where i want to use one js file which has two defines() in it, like this:

Filename: test.js

define('test1', ['jquery'], function() {
    return {
        method1 : function () {
            console.log("test1 - method 1");
        },

        method2 : function () {
            console.log("test1 - method 2");
        }
    }
});

define('test2', ['jquery'], function() {
    return {
        method1 : function () {
            console.log("test2 - method 1");
        },

        method2 : function () {
            console.log("test2 - method 2");
        }
    }
});

I also have a bootstrap,js file which is automatically loaded by the RequireJS framework:

require(['jquery', 'test', 'test2'], function ( $, t1, t2 ) {
    console.log(t1);
});

It does find the 2nd param, the 'test' file. Only, it returns a 'null'. It can't find 'test2' because it tries to look for a file called 'test2.js'. Actually i'd like to do something like:

require(['jquery', 'test.test1', 'test.test2'], function ( $, t1, t2 ) {
    console.log(t1);
});

But in anyway, i'd like to get a handler to both the objects. What am i doing wrong??

like image 603
w00 Avatar asked Mar 21 '12 14:03

w00


1 Answers

You cannot export two different modules like this. If you want to keep them as "submodules" of 'test', the right way would be to do:

define('test', ['jquery'], function() {
    var exports = {};
    exports.test1 = {
        method1 : function () {
            console.log("test1 - method 1");
        },

        method2 : function () {
            console.log("test1 - method 2");
        }
    };

    exports.test2 = {
        method1 : function () {
            console.log("test2 - method 1");
        },

        method2 : function () {
            console.log("test2 - method 2");
        }
    };

    return exports;
});

Then you can do:

require(['test'], function (test) {
    var test1 = test.test1;
});
like image 163
ggozad Avatar answered Oct 21 '22 22:10

ggozad