为了访问选定的项目,您可以在回调中使用常规而不是箭头函数,以便访问“this”,即 taskList
taskList.on('select', function(item, selected) {
console.log('got enter/select event', selected, item.content);
// this.selected and this.items[this.selected].content also available here
});
taskList.key('a', function() {
console.log('got "a"', this.selected, this.items[this.selected].content);
});
taskList.key('b', function() {
console.log('got "b"', this.selected, this.items[this.selected].content);
});
注意:列表组件应使用 指定parent: screen
,以便捕获关键事件,请参阅github issue
完整样本
const blessed = require('blessed');
const screen = blessed.screen({smartCSR: true});
screen.key(['escape', 'q', 'C-c'], function() { screen.destroy(); process.exit(0); });
const taskList = blessed.list({
parent: screen, // Can't capture events if we use screen.append(taskList)
width: 20,
keys: true,
items: ['a', 'b', 'c'],
style: {
selected: { bg: 'blue' },
item: { fg: 'magenta' }
}
});
taskList.key(['space', 'o'], function() {
console.log('got space or "o"');
this.enterSelected(); // Emit select and action event
});
taskList.on('select', function(item, selected) {
console.log(
'got an enter/select event',
'index: ', this.selected, '/' , selected, ';',
'vaule:', this.items[this.selected].content, '/', item.content
);
});
taskList.key('a', function() {
console.log('got an "a"', this.selected, this.items[this.selected].content);
});
taskList.key('b', function() {
console.log('got an "b"', this.selected, this.items[this.selected].content);
});
screen.render();