Skip to content

Instantly share code, notes, and snippets.

@voidfiles
Created June 16, 2012 19:59
Show Gist options
  • Select an option

  • Save voidfiles/2942379 to your computer and use it in GitHub Desktop.

Select an option

Save voidfiles/2942379 to your computer and use it in GitHub Desktop.
Simple Javascript Event Delegation
<html>
<head>
<title>Subscriber Test Page</title>
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.8.0r4/build/reset-fonts-grids/reset-fonts-grids.css">
<style type="text/css" media="screen">
body {
font-family: Myriad Pro, Helvetica, Arial;
font-size:138.5%;
}
h1 {
font-size:197%;
}
.container {
width:75%;
margin:2em auto;
background-color:#EEE;
border:1px solid #CCC;
}
</style>
</head>
<body>
<h1>Demo / Test page for Subscriber: Look at your console.</h1>
<script type="text/javascript">
var Subscriber = function () {
this.events = {};
};
Subscriber.prototype.create = function (event) {
if (this.events[event]) {
return;
}
this.events[event] = [];
return;
};
Subscriber.prototype.subscribe = function (event, callback, scope) {
if (!this.events[event]) { return; }
this.events[event].push({
callback: callback,
scope: scope
});
};
Subscriber.prototype.trigger = function (event, data) {
if (!this.events[event]) { return; }
var i,
callback,
scope,
output;
for (i in this.events[event]) {
callback = this.events[event][i].callback;
scope = this.events[event][i].scope;
if (!scope) {
output = callback(data);
} else {
output = callback.apply(scope, [data]);
}
}
return;
};
(function () {
var scope, data;
var mySubscriber = new Subscriber();
var myCallback = function () {
console.log("Test 1");
};
mySubscriber.create("testing");
mySubscriber.subscribe("testing", myCallback);
mySubscriber.trigger("testing");
var mySecondCallback = function () {
console.log(this.message);
};
scope = {
message: "Test 2"
};
mySubscriber.create("testing2");
mySubscriber.subscribe("testing2", mySecondCallback, scope);
mySubscriber.trigger("testing2");
var myThirdCallback = function (data) {
console.log("scope", this.message, "data", data.message);
};
scope = {
message: "Test 3"
};
data = {
message: "Test 3 data"
};
mySubscriber.create("testing3");
mySubscriber.subscribe("testing3", myThirdCallback, scope);
mySubscriber.trigger("testing3", data);
}());
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment