Skip to content

Instantly share code, notes, and snippets.

@Armen138
Created March 22, 2012 03:33
Show Gist options
  • Save Armen138/2155431 to your computer and use it in GitHub Desktop.
Save Armen138/2155431 to your computer and use it in GitHub Desktop.
Javascript Events
var MyEvents = function() {
"use strict";
var self = this,
eventList = {};
this.addEventListener = function(eventName, callback) {
if(!eventList[eventName]) {
eventList[eventName] = [];
}
eventList[eventName].push(callback);
};
this.removeEventListener = function(eventName, callback) {
var idx = -1;
if(eventList[eventName]) {
idx = eventList[eventName].indexOf(callback);
if(idx != -1) {
eventList[eventName].splice(idx, 1);
}
}
};
this.fireEvent = function(eventName, eventObject) {
var i,
eventFunction = "on" + eventName.charAt(0).toUpperCase() + eventName.slice(1);
if(eventList[eventName]) {
for(i = 0; i < eventList[eventName].length; i++) {
eventList[eventName][i](eventObject);
}
}
if(self[eventFunction]) {
self[eventFunction](eventObject);
}
};
//alias for fireEvent
this.emit = function(eventName, eventObject) {
this.fireEvent(eventName, eventObject);
};
//alias for addEventListener
this.on = function(eventName, callback) {
this.addEventListener(eventName, callback);
};
};
var Car = function(speed, distance) {
"use strict";
MyEvents.apply(this);
var self = this,
driving = false,
startDrivingAt = new Date().getTime(),
timeToDrive = distance / speed, //hours
driveInterval;
this.drive = function () {
var now = new Date().getTime();
if(now > startDrivingAt + (timeToDrive * 3600000)) {
self.fireEvent("arrived");
clearInterval(driveInterval);
} else {
self.fireEvent("driving");
}
}
driveInterval = setInterval(this.drive, 1000);
};
var car = new Car(50 /*kmph*/, 0.1 /*km*/);
car.addEventListener("driving", function() {
console.log("still driving!");
});
car.onArrived = function () {
console.log("arrived at destination!");
};
/*
car.addEventListener("arrived", function() {
console.log("arrived at destination!");
});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment