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
1 Answer
Reset to default 4In 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
版权声明:本文标题:Bind custom event to JavaScript object? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745298269a2652211.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论