간단한 프런트엔드 이벤트 프레임워크

4611 단어
인터넷의 한 자료를 참고하여 비고를 하다.

    
        js event demo
        
        
        
    
    
        

js event demo

<span style="color: #008000;">//</span><span style="color: #008000;"> </span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> EventEmitter() { </span><span style="color: #0000ff;">this</span>.events =<span style="color: #000000;"> {}; } </span><span style="color: #008000;">//</span><span style="color: #008000;"> </span> EventEmitter.prototype.on = <span style="color: #0000ff;">function</span><span style="color: #000000;">(ename, call){ </span><span style="color: #0000ff;">this</span>.events[ename] = <span style="color: #0000ff;">this</span>.events[ename] ||<span style="color: #000000;"> []; </span><span style="color: #0000ff;">this</span><span style="color: #000000;">.events[ename].push(call); } EventEmitter.prototype.emit </span>= <span style="color: #0000ff;">function</span><span style="color: #000000;">(ename, _){ </span><span style="color: #0000ff;">var</span> events = <span style="color: #0000ff;">this</span><span style="color: #000000;">.events[ename]; </span><span style="color: #008000;">//</span><span style="color: #008000;"> , ename</span> <span style="color: #0000ff;">var</span> args = Array.prototype.slice.call(arguments, 1<span style="color: #000000;">); </span><span style="color: #0000ff;">for</span>(<span style="color: #0000ff;">var</span> i = 0; i < events.length; i++<span style="color: #000000;">){ </span><span style="color: #008000;">//</span><span style="color: #008000;"> </span> events[i].apply(<span style="color: #0000ff;">null</span><span style="color: #000000;">, args); } } </span><span style="color: #0000ff;">function</span><span style="color: #000000;"> app(){ calltime </span>= 0<span style="color: #000000;">; </span><span style="color: #008000;">//</span><span style="color: #008000;"> </span> <span style="color: #0000ff;">this</span>.on('start',<span style="color: #0000ff;">function</span><span style="color: #000000;">(user, date){ calltime </span>+= 1<span style="color: #000000;">; console.log(</span>'event start: ' + user + " " + date + " " +<span style="color: #000000;"> calltime); }); </span><span style="color: #0000ff;">this</span>.on('start', <span style="color: #0000ff;">function</span><span style="color: #000000;">(user, date){ calltime </span>+= 1<span style="color: #000000;">; console.log(</span>'event start: ' + user + " " + date + " " +<span style="color: #000000;"> calltime); }) } app.prototype </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> EventEmitter(); </span><span style="color: #0000ff;">var</span> a = <span style="color: #0000ff;">new</span><span style="color: #000000;"> app(); </span><span style="color: #008000;">//</span><span style="color: #008000;"> </span> a.emit('start', 'fred', <span style="color: #0000ff;">new</span><span style="color: #000000;"> Date()); </span>

좋은 웹페이지 즐겨찾기