I can not find how to implement this (I apologize for the freestyle record):
//assign the event handler for the object "myObj"
myObj.onMyEvent = //do something
//if something happened somewhere, then run the event
MyEvent.fire();
The idea is that we call (generate) some custom event (MyEvent). We have an object "myObj" that is able to recognize the occurrence of the "MyEvent" and somehow (in his own way) to respond to it. In addition, we have other objects (diffrent sorts), that (in their own way) react to "MyEvent".
I know that there are "observer pattern" but I can not find a specific implementation.
Can you please tell where to read about it? Or in nature is generally not possible? Or it is done quite differently?
Update 1: no JS libs, please (jQuery, Prototype, YUI, ...)
no JS libs, please (jQuery, Prototype, YUI, ...)
I would seriously re-think this requirement. All of these libraries have solved this or similar problems many times.
But if you want to start from scratch, do something like this:
window.customEvents = {
handlers : {
foo:[],
bar:[],
baz:[]
},
registerEventHandler:function(event, object, handler){
if(typeof(customEvents.handlers[event])=="undefined")
customEvents.handlers[event]=[];
customEvents.handlers[event].push([object, handler]);
},
fireEvent:function(eventName, data){
if(customEvents.handlers[event]){
for(var i = 0; i < customEvents.handlers[event].length; i++){
var handlerPair = customEvents.handlers[event][i];
handlerPair[1](handlerPair[0], data);
}
}
},
}
Usage:
// register event handler
customEvents.registerEventHandler(eventName, targetObject, handlerFunction)
// fire event
customEvents.fireEvent(eventName, data)
// handlerFunction will be passed two parameters: targetObject and event data
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With