[关闭]
@c-Ku 2017-11-03T07:32:14.000000Z 字数 533 阅读 594

【JS基础】订阅发布模式

JavaScript


最 新:https://www.zybuluo.com/c-Ku/note/934090

代码示例

  1. // Based on ES5
  2. var login = {};
  3. login.eventList = {};
  4. // 将函数推入数组中保存,待用
  5. login.listen = function(key, fn) {
  6. if (!this.eventList[key]) {
  7. this.eventList[key] = [];
  8. }
  9. this.eventList[key].push(fn);
  10. }
  11. login.trigger = function(key) {
  12. var fns = this.eventList[key];
  13. if (!fns || fns.length === 0) {
  14. return false;
  15. }
  16. for (var i=0; i<fns.length;i++) {
  17. fns[i]();
  18. }
  19. }
  20. // 订阅
  21. login.listen('loginSuccess', function() {
  22. console.log('显示用户头像');
  23. })
  24. login.listen('loginSuccess', function() {
  25. console.log('显示消息列表');
  26. })
  27. // 发布
  28. login.trigger('loginSuccess');
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注