js:访问在函数中创建的菜单对象

Pebble.JS: Acces a menu object created in a function

本文关键字:创建 菜单 单对象 函数 访问 js      更新时间:2023-09-26

简写:

我在一个函数中创建了一个菜单对象,但是我不能在主脚本中访问这个菜单对象。

完整说明:

在createMyMenu()函数中,我确实创建了一个带有一些项目的菜单对象,并显示了菜单。这工作得很好,用户可以通过使用Pebble智能手表上的按钮在菜单中上下移动。

问题是用户不能选择任何项,只能在菜单中导航。

如果我在主脚本中创建菜单对象,当然可以正常工作,但是如果我在函数中创建菜单对象,用户就不能选择任何菜单项。

问题:如何在函数中创建菜单,然后在主脚本中使用该菜单对象,就像在主脚本中创建菜单一样?

代码:

function createMyMenu()
{
// Some code to create the menu object myMenu. Works fine.
  myMenu.show();  // Also works fine, the menu and it contents are displayed.
  return myMenu; // No errors
}

和脚本

mainMenu = createMyMenu(); // Create the menu.
mainMenu.on('select', function(e) // This does not seem to be executed. 
{
  // Code to execute when the user selects a menu item.
}

我自己解决了这个问题,下面是一些工作代码:

var UI = require('ui');
function createMyMenu()
{
// Some code to create the menu object myMenu. Works fine.
var myMenu = new UI.Menu({
  backgroundColor: 'black',
  textColor: 'white',
  highlightBackgroundColor: 'white',
  highlightTextColor: 'black',
  sections: [{
    title: 'My Menu',
    items: [{
      title: 'First Item',
      subtitle: 'first subtitle'
    }, { 
      title: 'second Item',
      subtitle: 'Second subtitle'
    }, {
      title: 'Third Item',
      subtitle: 'Third subtitle'
    }]
  }]
}); 
 myMenu.show();  // Also works fine, the menu and it contents are displayed.
  return myMenu; // No errors
}
//***** THE SCRIPT ******
var mainMenu = createMyMenu(); // Create the menu.
mainMenu.on('select', function(e) // This does not seem to be executed. 
{
  // Code to execute when the user selects a menu item.
    console.log('Button pressed');
    console.log('Selected item #' + e.itemIndex + ' of section #' + e.sectionIndex);
  console.log('The item is titled "' + e.item.title + '"');
});