concept array in category electron

appears as: n array, array, rrays, rray
Electron in Action

This is an excerpt from Manning's book Electron in Action.

  • Open dialog boxes return an array consisting of the one or more files or directories selected by the user.
  • Electron includes the Menu and MenuItem modules for building menus. In theory, we could build a menu out of individual MenuItems, but this method can be tedious and error prone. As a convenience, Menu provides the buildFromTemplate() method that accepts an array of regular JavaScript objects. Internally, Electron creates the MenuItems based on the array you provided.

  • Menu.buildFromTemplate() allows developers to build a menu out of an array of JavaScript objects instead of having to use the MenuItem constructor.
  • Listing 9.5. Storing clippings in memory using an array: ./app/main.js
    const path = require('path');
    const {
      app,
      Menu,
      Tray,
      systemPreferences,
    } = require('electron');
    
    const clippings = [];                                              #1
    let tray = null;
    
    const getIcon = () => {
      if (process.platform === 'win32') return 'icon-light.ico';
      if (systemPreferences.isDarkMode()) return 'icon-light.png';     #2
      return 'icon-dark.png';
    };
    
    app.on('ready', () => {
      if (app.dock) app.dock.hide();
    
      tray = new Tray(path.join(__dirname, getIcon()));
    
      if (process.platform === 'win32') {
        tray.on('click', tray.popUpContextMenu);
      }
    
      updateMenu();                                                    #2
    
      tray.setToolTip('Clipmaster');
    });
    
    const updateMenu = () => {
      const menu = Menu.buildFromTemplate([
        {
          label: 'Create New Clipping',
          click() { null; }                                            #3
        },
        { type: 'separator' },
        ...clippings.map((clipping, index) => ({ label: clipping })),  #4
        { type: 'separator' },
        {
          label: 'Quit',
          click() { app.quit(); },
        }
      ]);
    
      tray.setContextMenu(menu);                                       #5
    };
    
    Figure 9.7. When clippings are added to the array, the menu is updated with a new menu item with the clipping’s content as the label.