There are many solutions to the problem, depending on how large your application is. The two solutions you mentioned are the most obvious. I would rather go for a third, based on the re-architecture of your code. The solution that I provide looks the same as the artist template.
First, create actions that require your common module, which are in this particular form -
var Action_One = function(commonItems) { this.commonItems = commonItems; }; Action_One.prototype.execute = function() {
Now create an action initializer that will programmatically initialize your actions as follows:
var ActionInitializer = function(commonItems) { this.commonItems = commonItems; }; ActionInitializer.prototype.init = function(Action) { var obj = new Action(this.commonItems); return obj; };
The next step is to create an action performer -
//You can create a more complex executor using `Async` lib or something else var Executor = function(ActionInitializer, commonItems) { this.initializer = new ActionInitializer(commonItems); this.actions = []; }; //Use this to add an action to the executor Executor.prototype.add = function(action) { var result = this.initializer.init(action); this.actions.push(result); }; //Executes all the actions Executor.prototype.executeAll = function() { var result = []; for (var i = this.action.length - 1; i >= 0; i--) { result[i] = this.action[i].execute(); } this.action = [] return result; };
The idea was to split each module so that in this case there was only one Executor
module, which depends on common properties. Now let's see how this will work -
var commonProperties = {a:1, b:2};
Thus, your program will be cleaner and more scalable. Shoot questions if it's not clear. Happy coding!
source share