I am about to create my own event-driven API in JavaScript.

Most JavaScript that currently exists, e.g. in-browser JS for controlling the DOM, lets you register event handlers like this:

object.on('eventname', function handler() {});

'eventname' is basically a magic string, which is generally recommended against (right?)

But I see this pattern in all sorts of JavaScript libraries.

So in creating my own, should I follow the same pattern, or should I limit users to only something like:

object.onEventName(function handler() {

Or is there another way.

  • 1
    You're asking a lot of JavaScript. JavaScript itself uses strings for event names, so I'm not sure you can get around this anyway. Since JavaScript is a dynamically-typed language, it won't check these things for you like a statically-typed language compiler would; and since the handler is an inline anonymous function, I'm not sure the name even matters. – Robert Harvey Apr 10 '19 at 0:04
  • @RobertHarvey I put the name for the handler to make my question more readable. "JavaScript itself uses strings for event names" — I know lots of JS historically does, but I have the opportunity to design my own API now and don't have to stick to what other APIs do (although that might be the best idea). I'm not sure what javascript being dynamically typed has to do with this. – theonlygusti Apr 10 '19 at 0:32
  • I'm not sure what javascript being dynamically typed has to do with this. -- The primary benefit of your pattern is so that a compiler can check the static types to make sure they line up. That doesn't happen in JavaScript. – Robert Harvey Apr 10 '19 at 2:07
  • @RobertHarvey oh I thought the benefit was to avoid magic strings. If there's no recommendation style-wise for any pattern other than .on('string', handler) then I guess I will just use that – theonlygusti Apr 10 '19 at 3:26
  • 1
    One way is to use an enumeration. Another is to embed it in the function name. The specific approach you take will depend on your tools. JavaScript does not have a formal compiler, so you cannot lean on that. There are however unit tests, browser tests, static analysis tools, etc... figure out how to lean on these. The aim is for it to blindingly obvious when a change was not correctly propagated throughout the system. A magic string is rarely if every blindingly obvious when it is incorrect. JavaScript is an Typed language, why not create a Type to represent the event. .on(bobEvent(...)). – Kain0_0 Apr 10 '19 at 6:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.