1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| function Pub() { this.handler = {}; } Pub.prototype.on = function(type, handle) { if (!this.handler[type]) { this.handler[type] = []; } this.handler[type].push(handle); };
Pub.prototype.emite = function() { var type = Array.prototype.shift.apply(arguments); if (this.handler[type]) { var handles = this.handler[type]; handles.forEach(element => { element.apply(this, arguments); }); } };
Pub.prototype.off = function(type, handle) { if (this.handler[type]) { var handles = this.handler[type]; for (var i = 0; i < handles.length; i++) { if (handles[i] == handle) { handles.splice(i, 1); i--; } } } };
var p1 = new Pub(); function handle(name) { console.log(`this is the input name:${name}`); }
p1.on("add", handle); p1.on("add", function() { console.log(`这是另一个事件`); }); p1.off("add", handle); p1.emite("add", "wangpeng");
|