最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

C# like events in Javascript - Stack Overflow

programmeradmin4浏览0评论

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

private event EventHandler asdCompleted;

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

private void asd_pleted(object sender, EventArgs e)
{

}

and fire the event anywhere like in c#:

this.asdCompleted(this, null);

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

private event EventHandler asdCompleted;

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

private void asd_pleted(object sender, EventArgs e)
{

}

and fire the event anywhere like in c#:

this.asdCompleted(this, null);
Share Improve this question asked Sep 9, 2013 at 13:19 user2737037user2737037 1,1571 gold badge16 silver badges29 bronze badges 2
  • 3 developer.mozilla/en-US/docs/Web/Guide/API/DOM/Events/… – Leri Commented Sep 9, 2013 at 13:21
  • take a look at my answer to this similar question stackoverflow./questions/15963984/… – Khanh TO Commented Sep 9, 2013 at 13:27
Add a ment  | 

3 Answers 3

Reset to default 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();

If you use jQuery, then the answer is jQuery Callbacks

Something like this?

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

    document.asdCompleted('test');  
</script>
</body>
</html>
发布评论

评论列表(0)

  1. 暂无评论