Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# like events in Javascript

Tags:

javascript

c#

How can I create a new event/ like in c# in javascript?

private event EventHandler asdCompleted;

private void SetEventHandlers()
{
    this.asdCompleted += asd_completed;
}

private void asd_completed(object sender, EventArgs e)
{

}

and fire the event anywhere like in c#:

this.asdCompleted(this, null);
like image 337
user2737037 Avatar asked Mar 03 '26 03:03

user2737037


2 Answers

you can define a simple delegate list, like the one used internally by .NET, as follows

function createEvent() {
    var invokeList = [];

    var event = function() {
        for (var i = 0; i < invokeList.length; i++) {
            invokeList[i].apply(arguments);
        }
    }

    event.add = function(value) {
        invokeList[invokeList.length] = value;
    }

    return event;
}

var foo = {
    myEvent: createEvent()
}

foo.myEvent.add(function() { console.log('in my event'); });
foo.myEvent.add(function() { console.log('also in my event'); });

foo.myEvent();
like image 193
Robert Byrne Avatar answered Mar 05 '26 15:03

Robert Byrne


If you use jQuery, then the answer is jQuery Callbacks

like image 22
amartynov Avatar answered Mar 05 '26 16:03

amartynov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!