[关闭]
@bornkiller 2014-08-18T08:33:02.000000Z 字数 1981 阅读 2898

javascript sub/pub

javascript


二维码

qrcode

参考资料

  1. 发布/订阅:http://zh.wikipedia.org/wiki/%E5%8F%91%E5%B8%83/%E8%AE%A2%E9%98%85
  2. 自定义事件一: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent
  3. 自定义事件二: https://developer.mozilla.org/en-US/docs/Web/API/document.createEvent

前言

代码实现

  1. function SourceCribe () {
  2. // 生成发布/订阅器DOM节点
  3. var body = document.querySelector('body');
  4. if (!document.querySelector('.magazine')) {
  5. var element = document.createElement('mark');
  6. element.setAttribute("class", "magazine");
  7. body.appendChild(element);
  8. }
  9. this.magazine = document.querySelector('.magazine');
  10. // 消息发布实现
  11. this.publish = function (source, data) {
  12. if (!typeof source === 'string') {
  13. return false;
  14. }
  15. var oEvent = new CustomEvent(source, {
  16. bubbles: true,
  17. cancelable: false,
  18. detail:data
  19. });
  20. this.magazine.dispatchEvent(oEvent);
  21. };
  22. // 订阅实现,handler需要使用显式声明函数,不要使用匿名函数
  23. this.subscribe = function (source, handler) {
  24. if(!typeof source === 'string' || !typeof value === 'function') {
  25. return false;
  26. }
  27. this.magazine.addEventListener(source, handler, false);
  28. };
  29. // 取消订阅
  30. this.unsubcribe = function (source, handler) {
  31. if(!typeof source === 'string' || !typeof value === 'function') {
  32. return false;
  33. }
  34. this.magazine.removeEventListener(source, handler, false);
  35. };
  36. }
  1. (function(window){
  2. window.addEventListener('load',function(evt){
  3. var sourceCribe = new SourceCribe();
  4. var loveHandlerAlways = function (evt) {
  5. console.log("always " + evt.detail);
  6. };
  7. var loveHandlerEver = function (evt) {
  8. console.log("ever " + evt.detail);
  9. };
  10. sourceCribe.subscribe('love', loveHandlerAlways);
  11. sourceCribe.subscribe('love', loveHandlerEver);
  12. sourceCribe.publish('love','500 days with summer');
  13. sourceCribe.unsubcribe('love', loveHandlerAlways);
  14. sourceCribe.publish('love','500 days with summer');
  15. });
  16. })(window)

后续

联系方式

QQ/电子邮箱: 491229492

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注