Created
October 1, 2010 15:45
-
-
Save craveytrain/606371 to your computer and use it in GitHub Desktop.
Dumb Resilient Pub/Sub
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var sub = function (e, callback) { | |
var handler; | |
if (document.addEventListener) { | |
handler = function (evt) { | |
callback(); | |
}; | |
document.addEventListener(e, handler, false); | |
} else if (document.attachEvent) { | |
handler = function (evt) { | |
if (evt.propertyName == e) { | |
callback(); | |
} | |
}; | |
document.documentElement.attachEvent('onpropertychange', handler); | |
} | |
return [e, handler]; | |
}; | |
var unsub = function (args) { | |
var e = args[0], | |
handler = args[1]; | |
if (document.addEventListener) { | |
document.removeEventListener(e, handler, false); | |
} else if (document.attachEvent) { | |
document.documentElement.detachEvent('onpropertychange', handler); | |
} | |
}; | |
var pub = function (e) { | |
if (document.addEventListener) { | |
fauxEvent = document.createEvent('UIEvents'); | |
fauxEvent.initEvent(e, false, false); | |
document.dispatchEvent(fauxEvent); | |
} else if (document.attachEvent) { | |
if (!document.documentElement[e]) { | |
document.documentElement[e] = 0; | |
} else { | |
document.documentElement[e]++; | |
} | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sub('test', function () { | |
console.log('first sub'); | |
DOES_NOT_EXIST++; // this will throw an error | |
}); | |
var yankMe = sub('test', function () { | |
console.log('second sub'); | |
}); | |
console.log('First pass: should return 2 subs'); | |
pub('test'); | |
unsub(yankMe); | |
console.log('Second pass: should return 1 sub'); | |
pub('test'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment