How to implement a complete event system with Javascript?

前端 未结 3 1933
走了就别回头了
走了就别回头了 2021-01-27 17:43

I\'m creating a client-side dynamic blog engine. Now I need a event system to handle many actions from DOM elements and the engine. Such as the engine is loading a article,user

3条回答
  •  天涯浪人
    2021-01-27 17:59

    Recently, I wanted to add simple event listeners to vanilla JavaScript objects. This is the solution I came up with

    (This requires ecmascript >= 5)

    function Emitter () {
      var eventTarget = document.createDocumentFragment();
    
      function delegate (method) {
        this[method] = eventTarget[method].bind(eventTarget);
      }
    
      Emitter.methods.forEach(delegate, this);
    }
    
    Emitter.methods = ["addEventListener", "dispatchEvent", "removeEventListener"];
    

    Now a "class" that uses it

    function Example () {
      Emitter.call(this);
    }
    

    Let's try it out now!

    var e = new Example();
    
    e.addEventListener("something", function(event) {
      alert("something happened! check the console too!");
      console.log(event);
    });
    
    e.dispatchEvent(new Event("something"));
    

    Good luck!

提交回复
热议问题