Skip to content

Instantly share code, notes, and snippets.

@jeppeburchardt
Created April 9, 2014 15:21
Show Gist options
  • Save jeppeburchardt/10282520 to your computer and use it in GitHub Desktop.
Save jeppeburchardt/10282520 to your computer and use it in GitHub Desktop.
js vanilla class example
function inherits(Parent, Child) {
function F() {}
F.prototype = Parent;
Child.prototype = new F();
};
var VanillaClass = function () {
var self = this;
self.name = "VanillaClass";
self.listeners = {};
self.on = function (eventType, eventHandler, scope) {
if (!self.listeners[eventType]) {
self.listeners[eventType] = [];
}
self.listeners[eventType].push({eh:eventHandler, s:scope});
};
self.fire = function (eventType, payload, eventLoop) {
var loop = eventLoop || true;
if (self.listeners[eventType]) {
for (var i=0; i < self.listeners[eventType].length; i++) {
var handler = self.listeners[eventType][i];
var wrapper = function () {
handler.eh.call(handler.s, payload);
};
loop ? setTimeout(wrapper, 0) : wrapper();
}
}
};
self.json = function(url, successHandler, errorHandler, scope) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onreadystatechange = function() {
if (this.readyState === 4){
if (this.status >= 200 && this.status < 400){
var data = JSON.parse(this.responseText);
successHandler.call(scope, data);
} else {
errorHandler.call(scope, this.status);
}
}
};
request.send();
request = null;
}
};
var Player = function () {
VanillaClass.call(this);
this.name = "Player";
console.log("new Player");
this.on('play', this.onPlay, this);
};
inherits(VanillaClass, Player);
Player.prototype.play = function (param) {
console.log("Player.play " + this.name);
this.fire('play', 1337, true);
};
Player.prototype.onPlay = function (time) {
console.log('Player.onPlay ' + this.name);
};
var VideoPlayer = function () {
Player.call(this);
this.name = "VideoPlayer";
console.log("new VideoPlayer");
this.on('pause', this.onPause, this);
};
inherits(Player, VideoPlayer);
VideoPlayer.prototype.play = function (param) {
Player.prototype.play.call(this, param);
console.log("VideoPlayer.play " + this.name);
};
VideoPlayer.prototype.pause = function (param) {
console.log("VideoPlayer.pause " + this.name);
this.fire('pause', this.name, true);
};
VideoPlayer.prototype.onPause = function (time) {
console.log('VideoPlayer.onPause ' + this.name);
};
VideoPlayer.prototype.onPlay = function (time) {
console.log('VideoPlayer.onPlay ' + this.name);
};
var x = new VideoPlayer();
x.play('x');
x.pause('x');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment