admin管理员组

文章数量:1418964

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?

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?

Share Improve this question asked Mar 31, 2011 at 20:42 blabusblabus 8454 gold badges15 silver badges25 bronze badges 1
  • Are you asking, how you could do event binding/triggering in JavaScript or are you struggling with a specific set of tools? – skarmats Commented Mar 31, 2011 at 20:46
Add a ment  | 

1 Answer 1

Reset to default 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);
    }
}

本文标签: Bind custom event to JavaScript objectStack Overflow