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
3 Answers
Reset to default 6you 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>