tw16
tw16

Reputation: 29575

How to reduce repetitive javascript code

Is there anyway I can reduce the repetition below? I have only shown two code blocks but there are and will be many more of the same.

I have tried using arrays and loops, but unfortunately I could not get a working example. Thank you in advance.

E1 = new Audio('audio/E1.ogg');
E1.addEventListener('ended', function() {
  this.currentTime = 0;
  this.play();
}, false);

A1 = new Audio('audio/A1.ogg');
A1.addEventListener('ended', function() {
  this.currentTime = 0;
  this.play();
}, false);

EDIT : Using Jonathan's code below, I am still wondering whether it would be possible to do the equivalent of:

(E1,A1,x,x,x).addEventListener('ended', callback, false);
// I know this bit of code doesn't work

Upvotes: 2

Views: 1276

Answers (5)

David Ly
David Ly

Reputation: 31596

For the edited question, if you use the each function from Underscore.js you can do the following:

_.each([E1,A1,B1], function(audio) { 
    audio.addEventListener('ended', callback, false); 
});

Upvotes: 0

MikeM
MikeM

Reputation: 27405

something like

var addEndedEvent = function(elem) {
    elem.addEventListener('ended', function() {
        this.currentTime = 0;
        this.play();
    }, false);
}

addEndedEvent(new Audio('audio/A1.ogg'));

Upvotes: 2

WesleyJohnson
WesleyJohnson

Reputation: 1538

You should be able to do something like this. If you have more files, just add their name into the array fileNames.

var audioRefs = { }, fileNames = ['E1','A1','B1'], i, file;
for( i = 0; i < fileNames.length; i++ ) {
    file = fileNames[i];
    audioRefs[file] = new Audio('audio/' + file + '.ogg');
    audioRefs[file].addEventListener('ended', callback, false);
}

function callback() {
   this.currentTime = 0;
   this.play();
};

audioRefs will end up looking like....

audioRefs = {
   'A1': (reference to A1 Audio object),
   'B1': (reference to B1 Audio Object)
}

Upvotes: 0

sirbrialliance
sirbrialliance

Reputation: 3702

var files = ['audio/E1.ogg', 'audio/A1.ogg'];
//note that we cannot/should not use for(... in ...) - that won't do what you expect
for(var i = 0; i < files.length; ++i) {
    var audio = new Audio(files[i]);
    audio.addEventListener('ended', function() {
        this.currentTime = 0;
        this.play();
    }, false);
}

Upvotes: 2

Jonathan Sterling
Jonathan Sterling

Reputation: 18375

Since your callbacks are the same you can just bind them to a variable:

var E1 = new Audio('audio/E1.ogg');
var A1 = new Audio('audio/A1.ogg');

var callback = function() {
    this.currentTime = 0;
    this.play();
};

E1.addEventListener('ended', callback, false);
A1.addEventListener('ended', callback, false);

Upvotes: 7

Related Questions