I would like to create a custom event in JavaScript.
I have a WPF application with a WebBrowser inside, and a HTML page with JavaScript.
I work with a printer. When the state of the printer changes, it triggers an event in .NET.
Then, I call a JavaScript method OnPrinterStateChanged(state)
with the InvokeScript
function of the WebBrowser control.
The problem is that I have to implement the method OnPrinterStateChanged(state)
in my webpage. I can't change the name of the method or subscribe/unsubscribe to the event...
I would like to move the JavaScript method OnPrinterStateChanged(state)
in a separate JavaScript file.
What I want :
OnPrinterStateChanged(state)
of my separate .js file, then the JavaScript event is triggered and the function ChangeState
is called.I found some solutions but I didn't manage to make it work... What is the simplest way to do it?
js function subscribe(eventName, listener) { document. addEventListener(eventName, listener); } function unsubscribe(eventName, listener) { document. removeEventListener(eventName, listener); } function publish(eventName, data) { const event = new CustomEvent(eventName, { detail: data }); document.
Show activity on this post. let div: HTMLElement | null = document. getElementById("my_div"); let c_event = new CustomEvent<number>("build", {detail: 3}); div. addEventListener("build", function(e: CustomEvent<number>) { // change here Event to CustomEvent console.
Perhaps something like this?
function OnPrinterStateChanged(state) { var evt = new CustomEvent('printerstatechanged', { detail: state }); window.dispatchEvent(evt); } //Listen to your custom event window.addEventListener('printerstatechanged', function (e) { console.log('printer state changed', e.detail); });
An alternative solution would be to use function composition, but then it would be hard to remove specific listeners.
function OnPrinterStateChanged(state) {} function compose(fn1, fn2) { return function () { fn1.apply(this, arguments); fn2.apply(this, arguments); }; } //Add a new listener OnPrinterStateChanged = compose(OnPrinterStateChanged, function (state) { console.log('listener 1'); }); //Add another one OnPrinterStateChanged = compose(OnPrinterStateChanged, function (state) { console.log('listener 2'); });
EDIT:
Here's how you can do it with jQuery.
function OnPrinterStateChanged(state) { var evt = $.Event('printerstatechanged'); evt.state = state; $(window).trigger(evt); } //Listen to your custom event $(window).on('printerstatechanged', function (e) { console.log('printer state changed', e.state); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With