vendredi 18 mars 2022

What is the best way to setup public methods in a JS library [closed]

I am relatively new to JavaScript. My company develops an analytics solution written in TypeScript. It is practically a JS library that clients can import into their web pages. My task is to set up a public method that clients can use in order to trigger custom events in our system.

I did some research and from what I understand, there are different ways to do that:

  1. With post messages
  2. With custom events
  3. With public class/methods declared in the lib
  4. With global methods declared in the lib

Number 3 sounds the most logical to me, but I don't have enough experience to know what is the best practice. An ideal integration will look as follow:

<script src="..."></script> <!-- This is our library -->
<script>
    let lib = new ourLib();
    let data = {};

    // Allow the client to send custom events
    lib.triggerEvent('click', data); // this?
    ourLibTriggerEvent('click', data); // or this?
    window.ourLib.triggerEvent('click', data); // or this?
    // dispatch a custom event?
    // send a post message?
</script>

What would be the best practice for doing that? Am I completely off with my approach?

Thank you!

Aucun commentaire:

Enregistrer un commentaire