I am just getting into the world of javascript, coming from the world of classical inheritance. The following is a library I wrote to track when a webapp is idling and I wrote it like I write classical inheritance. But what I have heard about javascript is you have to completely forget how classical inheritance works.
I would love to see how a real javascript developer would write the following using prototypes and the likes.
var IdleListeners = new function(){
var self = this;
window.onmousemove = resetTimer;
window.onmousedown = resetTimer;
window.onclick = resetTimer;
window.onscroll = resetTimer;
window.onkeypress = resetTimer;
function resetTimer() {
for (var i = 0; i < self.listeners.length; i++) {
self.listeners[i].reset();
}
}
}
IdleListeners.listeners = [];
IdleListeners.add = function(idleFunction, timeout){
this.listeners.push(new IdleListener(idleFunction, timeout));
}
var IdleListener = function(idleFunction, timeout){
this.idleFunciton = idleFunction;
this.timeout = timeout;
this.reset = function(){
if (this.hasOwnProperty('interval')){
clearInterval(this.interval);
};
this.interval = setInterval(this.idleFunciton, this.timeout);
}
}
It is used by simply calling the following in your html/js file
IdleListeners.add(function(){
console.log("Idle!")
}, 1000);
"Idle!" would be called once every 1000 miliseconds when the mouse hasn't moved or no keys have been pressed.