Question

I'm working on a function that builds an html menu based on user input. Although it is possible to accept simple arguments or perhaps array types. I don't think it is a good practice, and it makes the code hard to read. How to create a readable object model for a function that builds a menu using it? The menu object, has menu names, their respective submenus,... individual items in submenus and if they are disabled or have functions bind to their click events. Consider the following simple object model for example:

var menu = {
menus : ['menu1','menu2'], 
subMenus : {'menu1' : 'subMenu1', 'menu2' : 'subMenu2'}, 
subMenuItems : {'subMenu1' : ['subMenu1','item1'], 'subMenu2' : ['item1','item2'] },
subMenu1 : ['item1', 'item2'],
enabled : {'item1' : function() { /* do something */ } },
disabled : ['item1']
}

I know this is not the best way to create an object model for a menu. Should I break this into smaller parts? Or am I totally wrong by trying to do this?

Was it helpful?

Solution

The purpose of object orientation keep the attributes and functionality of a given abstract thing in one place, and not strewn across multiple separate data structures, like you have here. Thankfully, Javascript allows you to very easily model each menu/submenu with their attributes literally.

In the same way that you've represented the names of the menus in an array, you can just as easily represent the menus themselves in an array, while encapsulating all of the data related to each particular menu within a simple structure.

Here I've modeled a simple object to represent each menu as a very simple object.

var menus = [
 {
  name : 'menu1',
  submenus : [
   {
    name : 'subMenu1',
    items : [
     {
      name : 'item1',
      enabled : false,
      action : function() { /* do something */ }
     }
    ]
   }
  ]
 },
 {
  name : 'menu2',
  submenus : [
   {
    name : 'subMenu2',
    items : [ /**etc.**/ ]
   }
  ]
 }
];

The menu has a name and an array of submenus, each submenu, in turn, also has a name and a list of items. Each item, again, has a name, a boolean representing whether it is disabled or not, and an action function (presumably you would bind this to a click event).

Here, the menu and submenu are almost identical data structures (other than the arbitrary distinction that a menu has submenus, whereas a submenu has items). You could simplify this even further by modeling the menu using a recursive data structure, like a tree, where each node is either a submenu or an action. Using recursion would allow you to create menus of arbitrary depth, add actions at any depth, and move submenus up and down with ease.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top