如何避免为AppleScript菜单的每个菜单项硬编码对应的处理函数
重构方案
核心逻辑是利用NSMenuItem自带的tag属性存储索引值,所有菜单项绑定同一个处理函数,触发时从发送者的tag属性读取对应索引即可,完全不需要生成多个后缀带数字的处理函数。
第一步:修改makeMenus生成菜单的逻辑
把原来拼接动态action名的逻辑删掉,统一绑定同一个actionsomeAction:,同时给每个菜单项设置tag为对应的索引值:
on makeMenus(selectedIndex as integer) newMenu's removeAllItems() -- 移除已有的菜单项 set menuItems to {"POC1", "POC2"} repeat with i from 1 to number of items in menuItems set this_item to item i of menuItems if i is equal to selectedIndex then set this_item to this_item & " " & (emoji's CHECK) -- 统一绑定同一个action,不再拼接数字后缀 set thisMenuItem to (current application's NSMenuItem's alloc()'s initWithTitle:this_item action:"someAction:" keyEquivalent:"") -- 把索引值存入菜单项的tag属性 thisMenuItem's setTag:i (newMenu's addItem:thisMenuItem) (thisMenuItem's setTarget:me) end repeat -- 单独创建退出菜单项 set thisMenuItem to (current application's NSMenuItem's alloc()'s initWithTitle:"退出" action:"quitAction:" keyEquivalent:"") (newMenu's addItem:thisMenuItem) (thisMenuItem's setTarget:me) end makeMenus
第二步:替换所有重复的处理函数为统一的单个处理函数
把原来的someAction1:、someAction2:等重复函数全部删掉,只保留下面这一个处理函数即可:
on someAction:sender -- 直接从发送者的tag属性拿到对应的索引值 set selectedIndex to sender's tag as integer updateStatus(selectedIndex) -- 如果需要获取菜单项名称,直接读取sender的title属性即可 -- set menuTitle to sender's title as text end someAction:
扩展说明
后续如果需要新增菜单项,只需要在menuItems数组里添加对应名称即可,不需要新增任何处理函数,完全符合DRY原则。
内容的提问来源于stack exchange,提问作者user3579815
相关产品推荐
相关产品推荐

