Dispatching custom event in Fitbit SDK

December 4, 2021 0 By addshore

I just upgraded my Fitbit charge 2 from 2016, to a Fitbit sense from 2020. After getting everything set up I took a quick look at the developer documentation and found myself in a web based IDE called Fitbit studio and before I knew it I had sideloaded a development demo app onto my new device.

And before I knew it, I had another side project in my repertoire. Make a cool little app that does stuff, just for me!

While developing the ability to switch between various “pages” I encountered the need to dispatch events with custom data. Though seemingly the Fitbit SDK doesn’t use the Javascript norms here and needs a slightly different approach. So here is what I learnt.

The error

While trying a regular modern JS approach here using the Event object and constructor, then passing this to dispatchEvent I ran into an issue.

function emitEvent(from, to) {
  let event = new Event('page-switch', {from:from,to:to})
  document.dispatchEvent(event);
}

document.addEventListener("page-switch", function (e) {
  console.log("Page switched from " + e.from + " to " + e.to)
}, false);Code language: JavaScript (javascript)

The SDK would complain that the Event object being used doesn’t have a field called type of type string.

[11:29:00]Unhandled exception: TypeError: Invalid argument: Event does not have a string type field
? at app/navigation.js:18,3
? at app/navigation.js:16,1
? at app/index.js:6,3

The fix

The SDK reference didn’t seem to be much help here at first glance, as it doesn’t relate things to the regular JS events. The MDN docs for Event seem to state that a type field of type string should exist, but none appeared to exist. A little more searching lead me to a community post that suggested using a regular object in place of a real Event.

Rather than using the Event object constructor, a regular object can be used. This object has a single requirement which is a type attribute of type string. Any extra event information can also just be added to this object.

function emitEvent(from, to) {
  document.dispatchEvent({type:'page-switch',from:from,to:to});
}

document.addEventListener("page-switch", function (e) {
  console.log("Page switched from " + e.from + " to " + e.to)
}, false);Code language: JavaScript (javascript)

I hope this short blog post helps anyone else searching for the TypeError: Invalid argument: Event does not have a string type field error in the Fitbit SDK context :)