2

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?

1
  • Are you asking, how you could do event binding/triggering in JavaScript or are you struggling with a specific set of tools? Commented Mar 31, 2011 at 20:46

1 Answer 1

4

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

2 Comments

Okay so I implemented the portion for Firefox et al (I'm not targeting IE at all). However from that article it seems that the 'element' variable needs to be a DOM object. In my case it's not, it's a JavaScript object. I tried using "this.initEvent(..." but no luck.
That is an unfortunate limitation. As a workaround, you could fire the custom event from the body element and listen for the event from the same.

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.