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
| let Observer = (() => { let _message = {} return { regist: function (type, fn) { if (typeof _message[type] === "undefined") { _message[type] = [fn] } else { _message[type].push(fn) } }, fire: function (type, args) { if (!_message[type]) { return } let events = { type, args: args || {}, } for (let i = 0, len = _message[type].length; i < len; i++) { _message[type][i].call(this, events) } }, remove: function (type, fn) { if (_message[type] instanceof Array) { for (let i = _message[type].length - 1; i >= 0; i--) { _message[type][i] === fn && _message[type].splice(i, 1) } } }, } })()
Observer.regist("test", function (e) { console.log(e.type, e.args.msg) }) Observer.fire("test", { msg: "this is some test message" })
|