I have a simple script I use to filter some results on a click of a button.
This is how I call this script on every page I use it:
myScript();
And then the script is: (this is just the part of the script, in reality the script itself is a long script that does some more stuff before the button click)
function myScript() {
// .. other part of the script ..
$("button.my-script.filter-button").on("click", filter)
function filter() {
let filters;
// calculating the filters . . .
// return filters;
}
}
I wanted to make this script work globally on every page that has it and trigger it on a click of a button with the classes .my-script
and .filter-button
. But then how can I detect when the filter()
method was called and get the result conveniently?
Because when it’s inside the wrapper I have no control over it (I want other people who need to use this script to be able to get the filters result without modifying the script code themselves)
2
Answers
You can extract the filter function from binded event and make it global …And call same function in binded event
I hope this will help.
The question provides no details on the way your script is supposed to work, how flexible it should be, should it be instantiated to provide independent instances, or as a singleton, whether you want to use a publish/subscribe pattern, or just use jQuery’s
.trigger()
etc… In fact there are so many ways, all different in implementation and usage.To stick as closely to your requirement and provided code, I suppose you just want to allow developers to use your script like
script()
– set and forget.If that’s the case, you might want to provide an
options
object argument with the desired methods that a developer can use like:Using the above, in the case a developer changes in HTML the button selector, he can then easily provide the new selector like:
If the developer does not want to read the filters data, and is happy with the default parameters, he can still use your script in its minimal format like
Learn more about different JavaScript patterns: https://www.patterns.dev/posts