首頁  >  文章  >  web前端  >  nodejs 中模擬實作 emmiter 自訂事件_node.js

nodejs 中模擬實作 emmiter 自訂事件_node.js

WBOY
WBOY原創
2016-05-16 15:14:192412瀏覽

nodejs 中模擬實作 emmiter 自訂事件

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <title></title>
  <script>
   function Emitter() {
    this.events = {}; //存放事件的地方
   }
   Emitter.prototype.on = function(type, cb) {
    var events = this.events; 
    events = events[type] = events[type] || [];
    events.push(cb);
   };
   
   Emitter.prototype.emit = function(type) {
    var args = [].slice.call(arguments, 1);
    var cbs = this.events[type], cb;
    while (cb = cbs && cbs.shift()) {
     cb.apply(this, args);
    }
   };
   var emitter = new Emitter();
   emitter.on('customevent', function(param) {
    alert(param);
   });
   emitter.on('customevent', function() {
    alert(1);
   });
   emitter.emit('customevent', 'xxx');
  </script>
 </head>
 <body>
 </body>
</html>

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn