北大侠客行MUD论坛

 找回密码
 注册
搜索
热搜: 新手 wiki 升级
12
返回列表 发新帖
楼主: jarlyyn

杰哥瞎扯蛋之事件驱动机制

[复制链接]
 楼主| 发表于 2024-4-28 15:25:40 | 显示全部楼层
正了下代码,做了个简单库

源代码:

https://github.com/hellclient-sc ... entbus/eventbus.lua

说明:
https://github.com/hellclient-sc ... /eventbus/readme.md

测试:
https://github.com/hellclient-sc ... b_eventbus/test.lua

附代码全文

  1. local M = {}
  2. M.EventBus = {}
  3. M.EventBus.__index = M.EventBus
  4. -- 创建事件总线函数
  5. function M.EventBus:new()
  6.     local e = {
  7.         _handlers = {}
  8.     }
  9.     setmetatable(e, self)
  10.     return e
  11. end

  12. -- 绑定事件
  13. -- 事件可以重复绑定
  14. -- 不应该依赖绑定顺序
  15. function M.EventBus:bindEvent(event, handler)
  16.     if self._handlers[event] == nil then
  17.         self._handlers[event] = {}
  18.     end
  19.     table.insert(self._handlers[event], (handler))
  20. end

  21. -- 解绑事件处理函数
  22. -- 解绑执行事件下所有绑定过的指定事件处理器
  23. -- event可以不存在
  24. function M.EventBus:unbindEvent(event, handler)
  25.     if self._handlers[event] == nil then
  26.         return
  27.     end
  28.     local result = {}
  29.     for i, v in ipairs(self._handlers[event]) do
  30.         if v ~= handler then
  31.             table.insert(result, v)
  32.         end
  33.     end
  34.     if (#result == 0) then
  35.         self._handlers[event] = nil
  36.     else
  37.         self._handlers[event] = result
  38.     end
  39. end

  40. -- 解绑某个事件所有的处理函数
  41. -- event可以不存在
  42. function M.EventBus:unbindAll(event)
  43.     self._handlers[event] = nil
  44. end

  45. -- 重置,放弃所有绑定
  46. function M.EventBus:reset()
  47.     self._handlers = {}
  48. end

  49. -- 触发事件,并将传入的context上下文传递给每一个处理函数
  50. -- event可以不存在
  51. function M.EventBus:raiseEvent(event, context)
  52.     if self._handlers[event] == nil then
  53.         return
  54.     end
  55.     for i, v in ipairs(self._handlers[event]) do
  56.         v(context)
  57.     end
  58. end

  59. -- 创建Eventbus的别名
  60. function M.new()
  61.     return M.EventBus:new()
  62. end

  63. return M
复制代码

北大侠客行Mud(pkuxkx.com),最好的中文Mud游戏!
您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|手机版|小黑屋|北大侠客行MUD ( 京ICP备16065414号-1 )

GMT+8, 2024-5-7 07:26 AM , Processed in 0.007942 second(s), 13 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表