I want to write a custom event and print to console obj.name in its callback function
But I get an error and need to get obj name as obj.detail.context.name
How can I solve it and print using obj.name line code instead of obj.detail.context.name
currently the strucure of obj in the callback is:
obj
CustomEvent { isTrusted: false } bubbles: false cancelBubble: false cancelable: false currentTarget: WindowdefaultPrevented: false detail: Object eventPhase: 2isTrusted: falseisTrusted: falsepath: Array[1]returnValue: truesrcElement: Windowtarget: WindowtimeStamp: 1446215160435type: "eat:done"proto: CustomEvent
You could augment the event object with your custom attributes (merge it with lodash or do it by yourself). The following example maybe gives you some insight;
// define the event
var event = new CustomEvent('test');
// add your custom arguments
event.customAttr = 'foo';
//the listener
window.addEventListener('test', function (e) {console.log(e)});
// fire it
window.dispatchEvent(event);
// logs: CustomEvent {isTrusted: false, customAttr: "foo"}
When registering a custom event, the returned value when it's triggered is of type CustomEvent.
This confusion is also apparent in your naming. Instead of:
MyEventsManager.on('eat:done', function(person){});
You're actually getting:
MyEventsManager.on('eat:done', function(event){});
If you want to use CostumEvents, this is the only way (You can't use custom events without using the CustomEvent object).
Perhaps you're looking for something simpler, like a callback manager:
function EventsManager(){
var callbacks = {};
return {
on: function(eventName, callback, context){
if(callbacks[eventName])
callbacks[eventName].push(callback.bind(context));
else
callbacks[eventName] = [callback.bind(context)];
},
trigger: function(eventName, data){
for(var i=0; callbacks[eventName] && i < callbacks[eventName].length; i++)
callbacks[eventName][i](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