'What is the best way to setup public methods in a JS library [closed]
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vitae tincidunt lacus. Praesent pellentesque sem mauris, et pulvinar diam viverra quis. Etiam eu feugiat sem. Donec id mauris vel nibh feugiat pulvinar. Quisque et orci mi. Duis tincidunt risus eu ligula maximus, tempor posuere orci dapibus. Aliquam faucibus tellus ligula, vel efficitur libero posuere nec. Cras augue dui, cursus finibus dictum nec, dignissim in dolor. Donec bibendum mollis nunc ac feugiat. Praesent feugiat, neque in euismod pharetra, lacus nunc tempus nisi, nec lacinia nisl nisi at dolor. Integer lobortis rhoncus mauris sit amet mollis.
Solution 1:[1]
If your library is being included on a webpage without bunding - that is, with
<script src="..."></script>
<script>//other client script</script>
then the most sensible approach by far (the one that the vast majority of these sorts of libraries implement) is to create an object that's accessible globally that provides an interface for all your library properties and methods. Dispatching a click event to the script tag doesn't make sense. Rather, have your library do something like:
window.theLibrary = (() => {
const theLibraryNamespace = {};
// lots and lots and lots of code that assigns stuff to theLibraryNamespace
return theLibraryNamespace;
})();
Then, to interface with it, the other scripts on the page would do something like
theLibrary.sendMessage('someEventName', eventData);
or maybe
theLibrary.doX(eventDataForX)
(with whatever sort of function signature(s) fits your expected use case best)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CertainPerformance |
