How to implement a complete event system with Javascript?

前端 未结 3 1902
走了就别回头了
走了就别回头了 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:49

    You could implement mediator pattern:

    http://addyosmani.com/resources/essentialjsdesignpatterns/book/#mediatorpatternjavascript

    In this book is everything you need to know about it.

    0 讨论(0)
  • 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!

    0 讨论(0)
  • 2021-01-27 18:13

    class SimpleEvent {
      constructor() {
        this.onEvent = {}
        this.handler = function(funct, name) {
          var owner = this
          var name = name
          this.onEvent[name] = funct
          var remove = function() {
            delete this.owner.onEvent[this.name]
            delete this.owner
            delete this.name
            delete this.remove
          }
          if ((((!(remove == undefined && name == undefined)) && (remove == undefined || name == undefined)))) {
            throw new Error("-_-")
          } else {
            return (remove == undefined || name == undefined) ? (undefined) : ({
              remove: remove,
              name: name
            })
          }
        }
      }
      Fire() {
        for (var i in this.onEvent) {
          this.onEvent[i](arguments)
        }
      }
    }

    0 讨论(0)
提交回复
热议问题