Skip to content

Conversation

@SimpleCodeCX
Copy link

本题目是基于以下思路来完成的:
1、在Delegator中定义一个events来存放所有注册过的事件列表
2、采用DOMNodeInserted来监听#container是否有新元素插入(appendChild),当有新元素添加时,从events中找出合适的事件绑定到新元素上

@miniflycn
Copy link
Member

miniflycn commented Nov 15, 2018

Delegator的原理进把事件绑定放在 root 节点。所以测试跑通,但实现是错的。

@SimpleCodeCX
Copy link
Author

   constructor(selector/* root选择器 */) {
      // TODO
      this.root = document.querySelector(selector);
      /**
       * 用于存储事件列表
       * [{ eventName: event,selector: selector,fn: fn}]
       */
      this.events = [];
      // 监听是否有新节点插入,如果有新节点插入,那么为新节点注册事件(如果有需要的话)
      this.root.addEventListener('DOMNodeInserted', (e) => {
        this.events.forEach(event => {
          let eles = document.querySelectorAll(event.selector);
          eles.forEach((ele) => {
            if (e.target == ele) {
              e.target.addEventListener(event.eventName, event.fn)
            }
          });
        });
      }, false);
    }

我不是绑定在root节点上哦,我是绑定的新添加的元素上(e.target)

@miniflycn
Copy link
Member

就是不能这么绑啊,这么绑就没必要设计delegator这种东西啦~

@SimpleCodeCX
Copy link
Author

哦哦,也是,这样就不属于delegator模式了

@SimpleCodeCX
Copy link
Author

参考了其他大佬的代码,这次实现了真正的委托了

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants