Lukas
Lukas

Reputation: 7734

How to call many functions with requireJS

I have two files: main.js and events.js.

In main.js i have defined some functions, which look's like this:

define(["jquery"], function() {

    var a =  {
       function_a: function(){
         some_actions;
       }
    }

    var b =  {
       function_b: function(){
         some_actions;
       }
    }

    return a, b;
});

and in events.js i have some calls for this functions:

require(['jquery','app/main'], function($, a){
    selector.on('click', function(){
        a.function_a();
    });
});

require(['jquery','app/main'], function($, b){
    selector.on('click', function(){
        b.function_b();
    });
});

Something is wrong because i can't call more than one of this functions, can anybody help?

Upvotes: 0

Views: 46

Answers (1)

Piotr Stapp
Piotr Stapp

Reputation: 19828

Instead of return a,b which is invalid statement you need to return an object for example: return {'a':a, 'b':b}

Then in your code you can write:

require(['jquery','app/main'], function($, obj){
    selector.on('click', function(){
        obj.a.function_a();
        obj.b.function_b();
    });
});

You could use also array. Then return will be return [a,b] and in require function:

require(['jquery','app/main'], function($, obj){
    selector.on('click', function(){
        obj[0].function_a();
        obj[1].function_b();
    });
});

Upvotes: 2

Related Questions