3

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

3 Answers 3

6

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();
Sign up to request clarification or add additional context in comments.

Comments

3

If you use jQuery, then the answer is jQuery Callbacks

Comments

1

Something like this?

<html>
<body>
<script>
    document.asdCompleted = function(s){
            alert(s);
        }

    document.asdCompleted('test');  
</script>
</body>
</html>

1 Comment

I think not exactly, because this approach lacks the capability of adding serveral handlers to the same "event".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.