blabus
blabus

Reputation: 845

Bind custom event to JavaScript object?

I can't figure out how to do it. It would seem to be something like this:

function MyObject() {
    this.fireEvent("myEvent");
}

And then in a separate JavaScript file:

var obj = new MyObject();
obj.addEventListener("myEvent", function() {
    alert("Event Fired");
});

But of course it doesn't work. My question is, how would I go about doing something like that?

Upvotes: 2

Views: 7045

Answers (1)

Jacob
Jacob

Reputation: 78890

In your example, you're firing the event immediately in the constructor (before the event listener is attached). Try moving the firing logic into a separate function.

Update:

Also, it seems like you're not firing an event properly. See this article for more information on how to properly fire events in a cross-browser manner. From that article:

function fireEvent(element,event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}

Upvotes: 4

Related Questions