Reputation: 341
[I'm a total newbie to Javascript so take it slow.]
I'm working on an app in node.js which will have a list of plugins. Each "plugin" should be a function (or 2) that can take a string and do something with it. The app should call each plugin in turn and pass it the string. Depending on the result it might call another function in that plugin etc...
What's the best way to design this in Javascript? I don't mind having to modify the app to add every plugin as its developed but would rather avoid having to do this a lot.
Right now I'm just thinking created a module for every module then "require" it within the primary app and call the function but that seems cludgy for a few reasons (a) I need to change the parent app quiet a bit for every new plugin, (b) there's no interface I can enforce on the plugins. I was kind of hoping there was some sort of contract I could force the plugins to respect.
Upvotes: 1
Views: 1366
Reputation: 198388
You can list the plugin directory, and require each file. If each file adds a function to an existing object (say, myapp.plugins
), you can just forEach
the object and invoke each function. You can't really enforce a contract in the code without doing weird things like invoking an AST parser; you're better off doing unit testing on plugins to make sure they work in isolation.
EDIT:
Can you elaborate a bit on this part: "If each file adds a function to an existing object (say, myapp.plugins), you can just forEach the object and invoke each function."?
var invokePlugins = function() {
var args = arguments.slice(0);
myapp.plugins.forEach(function(plugin) {
plugin.apply(plugin, args);
});
}
invokePlugins("this", "gets", "passed to", "each plugin");
Your architecture is unclear, so this is just a very rough idea of what you could do.
Upvotes: 1