@bornkiller
2014-08-18T16:33:02.000000Z
字数 1981
阅读 3027
javascript
function SourceCribe () {
// 生成发布/订阅器DOM节点
var body = document.querySelector('body');
if (!document.querySelector('.magazine')) {
var element = document.createElement('mark');
element.setAttribute("class", "magazine");
body.appendChild(element);
}
this.magazine = document.querySelector('.magazine');
// 消息发布实现
this.publish = function (source, data) {
if (!typeof source === 'string') {
return false;
}
var oEvent = new CustomEvent(source, {
bubbles: true,
cancelable: false,
detail:data
});
this.magazine.dispatchEvent(oEvent);
};
// 订阅实现,handler需要使用显式声明函数,不要使用匿名函数
this.subscribe = function (source, handler) {
if(!typeof source === 'string' || !typeof value === 'function') {
return false;
}
this.magazine.addEventListener(source, handler, false);
};
// 取消订阅
this.unsubcribe = function (source, handler) {
if(!typeof source === 'string' || !typeof value === 'function') {
return false;
}
this.magazine.removeEventListener(source, handler, false);
};
}
(function(window){
window.addEventListener('load',function(evt){
var sourceCribe = new SourceCribe();
var loveHandlerAlways = function (evt) {
console.log("always " + evt.detail);
};
var loveHandlerEver = function (evt) {
console.log("ever " + evt.detail);
};
sourceCribe.subscribe('love', loveHandlerAlways);
sourceCribe.subscribe('love', loveHandlerEver);
sourceCribe.publish('love','500 days with summer');
sourceCribe.unsubcribe('love', loveHandlerAlways);
sourceCribe.publish('love','500 days with summer');
});
})(window)
QQ/电子邮箱: 491229492