0

I'm going to attempt to build a data-driven menu for my web-app. The goal is to be able to serve different menu options to different users from an API. The hope is that the server could return a JSON object that defines the menu. The challenge I'm facing is how to define what the menu options do.

let menu = {
  "settings": {
    "label": "Settings",
    "icon": "settings.png",
    "type": "menu",
    "subitems": {
        "darkmode": {
          "label": "Dark Mode",
          "type": "toggle",
          "???": "???"
        },
        "other": {
          "label": "Some other setting",
          "type": "action",
        },
    } 
  },
  "profile": {
    "label": "Profile",
    "icon": "profile.png",
    "type": "link",
  }
}

It would be easy enough to iterate through the object and populate the menus, but in the example data above, how might I "toggle" the dark mode setting?

The only thought I've come up with is to have it be a link to something like "index.html?action=toggleDarkMode" then perform the appropriate method. This is obviously not ideal.

I've done some googling for "Javascript Data Driven Menu" but haven't had much luck. It's mostly dynamic drop downs or straight up nav links.

I've also determined/discovered it's a bad idea to just define methods in the JSON.

Sorry if this question is too vague, but any direction would be appreciated.

  • who is calling this api and why do they want your menu rather than their own? – Ewan Jul 6 '18 at 13:05
  • Are you serious? – Scott Beeson Jul 6 '18 at 13:06
  • yes. it seems like an api can't provide a menu for random applications, how would it know what pages are on the website calling it? – Ewan Jul 6 '18 at 13:08
  • There are no "random applications"... I'm building a webapp. I'm calling the API. User A might get menu items that User B does not, as defined in a database. – Scott Beeson Jul 6 '18 at 13:09
  • It's not a public API. – Scott Beeson Jul 6 '18 at 13:11
2

One of the options is to have action key for each of "acting" menu items, e.g.

let menu = {
    ...
    "darkmode": {
        ...
        "action": "toggleDarkMode",
    },
    ...
};

You may have an object listing all possible actions, e.g.

let actions = {
    toggleDarkMode: toggleDarkMode, // a function defined somwhere else
    yetAnotherAction: () => { console.log('ACTION!'); },
};

Now assuming you have menuItem referring to either of "acting" menu items you may just call actions[menuItem.action]();

The problem is that any your action can be called (e.g. using developers console) disregarding the fact it is not referred to in your menu.

Hope the above helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.