Firing and capturing custom events

前端 未结 4 580
青春惊慌失措
青春惊慌失措 2020-12-29 10:15

Imagine this scenario (it\'s really just a scenario):

  • I have a global counter that gets incremented on every mouse click.
  • when I reach 50 clicks, I
4条回答
  •  -上瘾入骨i
    2020-12-29 10:37

    function fireEvent(name, target) {
        //Ready: create a generic event
        var evt = document.createEvent("Events")
        //Aim: initialize it to be the event we want
        evt.initEvent(name, true, true); //true for can bubble, true for cancelable
        //FIRE!
        target.dispatchEvent(evt);
    }
    
    function foobar() {
        alert("foobar");
    }
    
    function testEvents() {
        window.addEventListener("foobar", foobar, false); //false to get it in bubble not capture.
        fireEvent("foobar", document);
    }
    

    Found this code with 1 minute of Google Search. http://the.unwashedmeme.com/blog/2004/10/04/custom-javascript-events/

提交回复
热议问题