Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
100
rated 0 times [  104] [ 4]  / answers: 1 / hits: 83572  / 10 Years ago, mon, april 28, 2014, 12:00:00

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 :




  • Subscribe/Unsubscribe to the event in my HTML page and decide what I want to do when the event is triggered (ex. : function ChangeState)

  • When the .NET event is triggered, it calls the 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?


More From » events

 Answers
65

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);
});

[#71270] Friday, April 25, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leslijessalyng

Total Points: 650
Total Questions: 85
Total Answers: 109

Location: Croatia
Member since Mon, Sep 6, 2021
3 Years ago
leslijessalyng questions
Fri, Feb 21, 20, 00:00, 4 Years ago
Tue, Jul 30, 19, 00:00, 5 Years ago
Fri, Jul 5, 19, 00:00, 5 Years ago
Wed, Mar 13, 19, 00:00, 5 Years ago
;