var button = new Button();
button.Click += (sender, ev) => {
MessageBox.Show("Hello, world!");
};
You can define events within your own classes and fire them easily:
public delegate void MyEventHandler();
public event MyEventHandler MyEvent;
// ... lots of code ...
// ... in some method that triggers the event:
if (MyEvent != null){
MyEvent();
}
Turns out this is fairly easily implemented in Javascript. This code here should do the trick:
function createEvent(eventName, obj){
var event = function() {
var ob;
for (var i = 0; i < obj[eventName].observers.length; i++){
ob = obj[eventName].observers[i];
ob.apply(ob, arguments);
}
};
event.observers = [];
event.add = function(observer) {
event.observers.push(observer);
};
event.remove = function(observer) {
var i = event.observers.indexOf(observer);
if (i >= 0){
event.observers.splice(i, 1);
}
};
obj[eventName] = event;
}
Now you can go like this:
var obj = {};
createEvent("test", obj);
obj.test.add(function(){
alert("Hello, world!");
});
obj.test();
You can try it by clicking here.
No comments:
Post a Comment