Reputation: 705
I have a little library with common functions. It is structured like this:
var $MY_APP = (function() {
return {
GROUP1: {
method1 : function(){ console.log("Test"); },
method2 : function(){}
},
GROUP2: {
method1 : function(){ },
method2 : function(){}
},
GROUPX: {
method1 : function(){ $MY_APP.GROUP1.method1(); },
method2 : function(){}
},
}
})();
Is it possible from any method from GROUPX, invoking another group method without doing it like in the example?
$MY_APP.utils.GROUP1.method1();
Hoy to catch this in this case? Is it possible?
Upvotes: 0
Views: 48
Reputation: 48347
Have you considered using a full module/loader system, such as Require.JS? It could be helpful, especially if you get more groups, or split them across multiple files.
To get the version you have now working, you simply need to use intermediate variables. Rather than declaring all modules at once, in the return statement, declare them earlier and assign them to variables within the app. That allows them to reference one another more simply, and you can later return them all in a group.
For example:
var message = $("#message");
var $MY_APP = (function() {
var GROUP1 = {
method1: function() {
message.text("Test");
},
method2: function() {}
};
var GROUP2 = {
method1: function() {},
method2: function() {}
};
var GROUPX = {
method1: function() {
GROUP1.method1();
},
method2: function() {}
};
return {
GROUP1: GROUP1,
GROUP2: GROUP2,
GROUPX: GROUPX
}
})();
$MY_APP.GROUP1.method1();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="message"></div>
To allow groups to reference other groups that were declared later, you can either use local variables for the methods within the group, or declare all the groups at the beginning.
Bear in mind that if you start declaring things early without initializing them, and referencing them later, you need to make sure not to call a method before all the groups it depends on have been initialized. This can lead to a fair amount of book-keeping, which is where module systems like Require come in handy.
Upvotes: 1