如何避免对每个菜单项的处理程序进行硬编码?

How can I avoid hard coding the handlers for each menu item?

我有一个保持打开状态的 AppleScript 应用程序,它创建了一个包含许多菜单项的菜单。映射的处理程序是重复的,只是其索引不同。我怎样才能重构这段代码来干掉它?

on makeMenus(selectedIndex as integer)
    newMenu's removeAllItems() -- remove existing menu items

    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)
        set thisMenuItem to (current application's NSMenuItem's alloc()'s initWithTitle:this_item action:("someAction" & (i as text) & ":") keyEquivalent:"")
        (newMenu's addItem:thisMenuItem)
        (thisMenuItem's setTarget:me)
    end repeat

    -- Create the Quit menu item separately
    set thisMenuItem to (current application's NSMenuItem's alloc()'s initWithTitle:"Quit" action:("quitAction:") keyEquivalent:"")
    (newMenu's addItem:thisMenuItem)
    (thisMenuItem's setTarget:me)
end makeMenus

重复处理程序是:

on someAction1:sender
    updateStatus(1)
end someAction1:

on someAction2:sender
    updateStatus(2)
end someAction2:

如果我可以从 someAction 处理程序中的参数派生菜单项名称或索引,那将让我有一个处理程序来处理所有菜单项。

动作处理程序的 sender 参数将是调用该动作的 object。在这种情况下,发件人将是特定的 menuItem,因此常见的操作处理程序可以使用 属性,例如发件人的标题。

请注意,由于它将是 Cocoa object,您需要将标题强制转换为 AppleScript 字符串,例如:

on doAction:sender
    set menuTitle to (sender's title) as text
    if menuTitle is "this" then
        doThis()
    else if menuTitle is "that" then
        doThat()
    else
        doOther()
    end if
end doAction: