Reputation: 10828
I have multiple connections that connect to external servers via socket. However on each will do actually same thing. What is DRY solution to this?
For example:
ami1
, ami2
, ami3
are connected to 3 servers.
var ami1 = new require('asterisk-manager')('port','host1','username','password', true);
var ami2 = new require('asterisk-manager')('port','host2','username','password', true);
var ami3 = new require('asterisk-manager')('port','host3','username','password', true);
I have to repeat for each one
ami1.keepConnected();
ami2.keepConnected();
ami3.keepConnected();
Every each one will do actually same thing.
ami1.on('response', function(evt) {
if () { }
if () { }
if () { }
});
ami2.on('response', function(evt) {
if () { }
if () { }
if () { }
});
ami3.on('response', function(evt) {
if () { }
if () { }
if () { }
});
Upvotes: 0
Views: 46
Reputation: 136104
Store the connections in an array:
var ami = [
new require('asterisk-manager')('port','host1','username','password', true),
new require('asterisk-manager')('port','host2','username','password', true),
new require('asterisk-manager')('port','host3','username','password', true)
];
Us a loop to keep them alive
for(var i=0;i<ami.length;i++)
ami[i].keepConnected();
(You could wrap that in a function keepAllConnected
if you make multiple calls to it)
And bind events the same way
for(var i=0;i<ami.length;i++){
ami[i].on('response', function(evt) {
if () { }
if () { }
if () { }
});
}
Upvotes: 3