Friday, November 15, 2013

Array forEach Synergy

Today I wanted to share another nice and small use case for the forEach loop for the intermediate/beginner javascript developer.

function AudioWrapper(src){//Simple audio wrapper
var audio = new Audio(), self = this;//create the audio element
audio.src = src;//set the source...
['play','stop','pause'].forEach(function(item){//play stop and pause hookup
var actualCommand = item === 'stop'?'pause':item;//when stopping, use pause instead
self[item] = function(){//set the function...
audio[actualCommand]();//call the pause or play function
if(item === 'stop')//and if stop is called...
self.currentTime(0);//go back to the start
};
});
this.currentTime = function(time){//small convenience function
return audio.currentTime=time||time===0?0:src.currentTime;//sets the current time or returns it
};
this.canPlay = function(){//just checks to see if the readyState is 4
return audio.readyState === 4;//ready state!
};
this.onReady = function(func){//Any function hooked here will be called 100% of the time
var args = [].slice.call(arguments, 1);//unless it isn't loaded
function checkReady(){//named function
if(self.canPlay())//check to see if it can be played
func.apply(self, args);//call the function...
else
setTimeout(checkReady,100);//check in a few seconds.
}
checkReady();//start up!
};
}
var x = new AudioWrapper(src);//create the Audio
x.onReady(function(playLength){//hook up a function...
x.play();
setTimeout(x.stop, playLength);
},10000);
view raw AudioWrapper.js hosted with ❤ by GitHub


As a disclaimer, my code isn't perfect, it can be optimized, and my goal isn't give you snippets of code to steal. However, I do this to show you how to make your own javascript functions yourself. Take my code and tweak it, add some useful functions that may help you finish your project.

I hope my samples help grow and motivate you to strive and become a better programmer.

In functional health,
-Josh

No comments:

Post a Comment