3

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

1
  • can you provide jsfiddle? Commented Oct 30, 2015 at 14:32

2 Answers 2

2

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"}
Sign up to request clarification or add additional context in comments.

Comments

2

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);
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.