How to add eventListener highlight buttonLockup?

338 Views Asked by At

I want add eventListener highlight buttonLockup with stackTemplate. Can you guide to use this? Thanks,

1

There are 1 best solutions below

0
On

The event system in TVJS is extremely similar to that in a web browser. After all, it's just JS and a DOM. MDN's documentation on Event Handlers should be mostly relevant

To add an event listener to a specific button, just find that button (using ID or name or whatever), and use addEventListener.

var myButton = doc.getElementByName('buttonLockup')
var onSelect = function(ev) {
  console.log('Button selected!')
}
myButton.addEventListener('select', onSelect)

However, depending on your use case, I've found Apple's approach in their sample apps to be quite useful. They rely on the fact that events bubble up to the root of the template, and just listen to them there. So for example:

// Given a TVML document has been presented with this somewhere in it
<buttonLockup action="doSomething">Do something</buttonLockup>

// When it's selected, doSomething
var globalOnSelect = function(ev) {
  var target = ev.target;
  var action = target.getAttribute('action')

  if (action === 'doSomething') {
    console.log('Do Something button selected');
    doSomething();
  }
}

doc.addEventListener('select', globalOnSelect);