getting a this. with addEventListener and attachEvent

When writing script for asp.net controls, it's common to want to attach event handlers via script to elements. For some time now, I've been playing with the various ways to do this in order to find the “Best Way”.

My list of things I wanted to acheive were:

  1. I wanted to have “this.” to refer to the element which has caused the event, such as the button being clicked.
  2. I wanted it to be non-destructive. I wanted to make sure that nobody else's handlers where removed when I added mine.
  3. I wanted it to work on v4-era + browsers.

As of last nite around 2am, I'm fairly satisfied that the following method is pretty much the best that's going to happen.

function XBrowserAddHandler(target,eventName,handlerName) { 
  if ( target.addEventListener ) { 
    target.addEventListener(eventName, function(e){target[handlerName](e);}, false);
  } else if ( target.attachEvent ) { 
    target.attachEvent("on" + eventName, function(e){target[handlerName](e);});
  } else { 
    var originalHandler = target["on" + eventName]; 
    if ( originalHandler ) { 
      target["on" + eventName] = function(e){originalHandler(e);target[handlerName](e);}; 
    } else { 
      target["on" + eventName] = target[handlerName]; 
    } 
  } 
}

Here's an example of how it would be used. (The following code assumes that a couple buttons exist on the form, with an appropriate Array-Declaration with their names, and a call to the Init method.

function Demo_Init() { 
  var theForm = document.forms[0]; 
  for( var i = 0; i < Demo_Buttons.length; i++ ) { 
    var theButton = theForm[Demo_Buttons[i]]; 
    theButton.MyMessage = "This Is The Script-Attached Message On " + Demo_Buttons[i]; 
    theButton.ClickHandler = Demo_ClickHandler; 
    XBrowserAddHandler(theButton,"click","ClickHandler"); 
  } 
} 
function Demo_ClickHandler(e) { alert( this.MyMessage ); } 

using the XBrowserAddHandler method, it doesn't matter if the element declares it's own onclick attribute, everything still runs as expected.

As for my requirements: #1 is satisfied by making the handler a method on the element itself. This usually doesn't play well with the addEventListener/attachEvent stuff, so lets look at why it works.

target.addEventListener(eventName, function(e){target[handlerName](e);}, false);

instead of adding the function itself, i actually declare an anonymous function as the real handler, and this function calls the intended handler thru the given “target” argument, preserving “this”. For those of you coming from a SmallTalk or LISP background, you may be able to correct me here, but the feature being used here is called a “Closure”, because the local args “target”, and “handlerName” are actually kept around for the time that the anonymous event handler function is called, long after they go out of the scope of XCrossBrowserAddHandler. It's some pretty neat stuff, and shows how javascript is one of the coolest languages ever. It's OO, it's Functional, it's Procedural. Whatever you need, it can do it.

103 Comments

  • LOL... just did the same thing here two days ago.

  • Something about this solution just occurred to me. Is there a way to remove an event handler using this scheme (assuming the attachEvent/detachEvent code path)?

  • I don't think so... but that's ok with me. I have yet to ever need to detach an event.

  • as an addendum to my last comment... notice that &quot;ability to remove event handler&quot; isn't on my list'o'requirements.

  • Andy, I like your idea! I do a lot of ASP.Net control development at my company and can feel your pain on most of this stuff.



    But I have some questions with this implementation:



    a) If you're going to support old browsers that don't have event listeners, why bother with the event listeners for any browser. Aren't you just creating more code, more code paths, and more possible errors? Personally, I'd rather everything worked as close to the same on every supported platform as possible.



    b) I don't like having to specifically assign the function reference to an expando of the element before adding it as a handler. I'd rather do it all in one step.



    c) There are known memory leaks in IE with closures that include references to HTML elements. These mostly manifest themeselves in long-running DHTML scenarios, not ASP.Net applications. But I avoid them as a matter of practice now, just in case.



    For these reasons, I've modified your original script; you can assign handlers in one step, the code path is essentially the same no matter the browser; and it avoids potential memory leaks a little more than your original.



    What think?



    [code]

    &lt;html&gt;

    &lt;head&gt;

    &lt;script&gt;

    function Demo_Init() {

    var theButton = document.getElementsByTagName(&quot;BUTTON&quot;)[0];

    theButton.MyMessage1 = &quot;hello 1&quot;;

    theButton.MyMessage2 = &quot;hello 2&quot;;

    XBrowserAddHandler(theButton, &quot;click&quot;, Demo_ClickHandler);

    XBrowserAddHandler(theButton, &quot;click&quot;, function(e) {

    alert(this.MyMessage2 + &quot; from &quot; + e.type);

    });

    }

    function Demo_ClickHandler(e) { alert( this.MyMessage1 + &quot; from &quot; + e.type ); }





    function XBrowserAddHandler(target,eventName,fnHandler) {

    var originalHandler = target[&quot;on&quot; + eventName];

    if ( originalHandler ) {

    // note that we have just created a memory leak in IE because the closures from

    // these two anonymous functions reference &quot;target&quot;, an HTML element. nuts :(

    target[&quot;on&quot; + eventName] = function(e){

    XBrowserApplyHandler(this, originalHandler, e);

    XBrowserApplyHandler(this, fnHandler, e);

    };

    } else {

    target[&quot;on&quot; + eventName] = function(e) {

    XBrowserApplyHandler(this, fnHandler, e)

    };

    }

    }



    function XBrowserApplyHandler(target, fn, e) {

    if (!e) e = window.event;

    if (!e) alert(&quot;Problem with XBrowserApplyHandler: could not find event object.&quot;);



    if (Function.prototype.call) {

    fn.call(target, e);

    } else {

    target.__XBrowserElementApply = fn;

    target.__XBrowserElementApply(e)

    }

    }

    &lt;/script&gt;

    &lt;/head&gt;

    &lt;body onload=&quot;Demo_Init()&quot;&gt;



    &lt;button&gt;hello&lt;/button&gt;



    &lt;/body&gt;

    &lt;/html&gt;

    [/code]

  • a) that makes sense.

    b) that's an interesting approach, it never really occured to me to call handlers directly. I can see where it would be useful.

    c) I suppose so.



    All good points. I'll crawl back into my hole now :)

  • eek, no indent

    I forget, of course it works for other elements



    // same as document.getElementByID,

    // but with ns4 support

    var dummy= Script.getElementById('dummy');

    implementEvent(dummy);



    dummy.addEventListener(....)

  • Hello, I enjoy reading all of your post. I like to write a little comment to support you.

  • We're a gaggle of volunteers and opening a new scheme in our community. Your web site offered us with useful information to work on. You have performed an impressive task and our whole community will probably be thankful to you.

  • A person essentially assist to make seriously articles I might state.
    That is the first time I frequented your website page and thus far?
    I surprised with the research you made to create this particular post extraordinary.

    Great activity!

  • Koegel, l!! In fact, nowadays, we also have nail parlors, that give a beautiful manicure plus
    a soothing massage to the fingers and hands. Try using
    a combination of these two types of oils, basil, eucalyptus, lemon grass and
    ylang-ylang are good for oily skin, because they help normalize overactive sebaceous glands?
    ?

    Mike grafstein smt(c) certified sports massage therapistwhat is client handling?
    Designating that many therapists as lead and then strategically scheduling them in order to
    cover the entire work week would surely prove to be an ineffective solution if not a nearly impossible plan.
    . I've picked these oils for their relaxing, sensual, or refreshing qualities. But the trend has been changed in this modernize world and now i guess. In the current state, becoming a respiratory therapist could be a wise decision for students are usually a clever option as the number of older individuals within the nation is increasing at a rapid speed.

  • I have been exploring for a little for any high-quality articles or blog posts on this kind of
    area . Exploring in Yahoo I ultimately stumbled upon
    this site. Reading this information So i am glad to convey that I have an
    incredibly just right uncanny feeling I came upon just what I needed.
    I so much indisputably will make sure to do
    not disregard this web site and give it a look on a relentless basis.

  • What i do not understood is in truth how you are now not actually a
    lot more well-preferred than you may be now. You are so intelligent.
    You know therefore significantly when it comes to this
    topic, produced me individually imagine it from numerous various angles.
    Its like men and women are not fascinated until it's one thing to do with Lady gaga! Your personal stuffs great. All the time deal with it up!

  • Pretty great post. I just stumbled upon your
    blog and wished to mention that I have really loved browsing your blog posts.
    After all I'll be subscribing for your feed and I am hoping you write once more very soon!

  • Does your website have a contact page? I'm having a tough time locating it but, I'd like to
    shoot you an e-mail. I've got some recommendations for your blog you might be interested in hearing. Either way, great website and I look forward to seeing it improve over time.

  • Sweet blog! I found it while surfing around on Yahoo
    News. Do you have any tips on how to get listed in Yahoo News?

    I've been trying for a while but I never seem to get there! Thank you

  • Hey just wanted to give you a quick heads up. The words
    in your article seem to be running off the screen in Safari.

    I'm not sure if this is a formatting issue or something to do with web browser compatibility but I thought I'd post to let you
    know. The design and style look great though! Hope you get the problem resolved soon.
    Thanks

  • What's up colleagues, how is all, and what you wish for to say regarding this piece of writing, in my view its genuinely awesome for me.

  • Hello! I just wanted to ask if you ever have any problems with hackers?

    My last blog (wordpress) was hacked and I ended up losing several weeks of hard work due to
    no back up. Do you have any methods to prevent hackers?

  • If some one wants to be updated with most up-to-date technologies after that he
    must be pay a visit this site and be up to date all the time.

  • Howdy! Would you mind if I share your blog with my myspace group?
    There's a lot of people that I think would really appreciate your content. Please let me know. Cheers

  • Do you mind if I quote a few of your articles as long as
    I provide credit and sources back to your weblog?

    My website is in the exact same area of interest as yours and my users would genuinely benefit from some of the information you present here.

    Please let me know if this ok with you. Cheers!

  • Thanks for sharing your thoughts. I really appreciate your efforts and I am waiting for your further write ups thanks once again.

  • I don't write many remarks, but after reading through a few of the comments on getting a this. with addEventListener and attachEvent - Andy Smith's Blog.

    I do have a couple of questions for you if it's okay. Is it simply me or does it look like like some of the remarks come across like they are coming from brain dead folks? :-P And, if you are writing at other online sites, I would like to keep up with you. Could you make a list of all of your social sites like your linkedin profile, Facebook page or twitter feed?

  • Definitely imagine that which you stated.
    Your favourite reason seemed to be on the net the simplest thing to be mindful of.
    I say to you, I definitely get irked while other folks think about concerns that
    they plainly do not recognize about. You managed to
    hit the nail upon the top and also defined out the entire thing with no need side-effects , other people can take a signal.
    Will likely be again to get more. Thanks

  • Hello, i think that i saw you visited my weblog thus i came to return the prefer?

    .I am attempting to find things to improve my website!
    I guess its good enough to use some of your ideas!!

  • Hello, this weekend is good in support of me,
    as this occasion i am reading this enormous educational piece of writing here at
    my home.

  • Unquestionably believe that which you stated. Your favorite justification
    seemed to be on the internet the easiest thing to be aware of.
    I say to you, I certainly get annoyed while people consider worries that they plainly do not
    know about. You managed to hit the nail upon the top as
    well as defined out the whole thing without having side effect , people could take
    a signal. Will probably be back to get more. Thanks

  • Hello to every one, the contents present at
    this website are really awesome for people knowledge,
    well, keep up the nice work fellows.

  • Way cool! Some very valid points! I appreciate you writing this write-up and also the rest of the site is extremely good.

  • This article provides clear idea designed for the
    new users of blogging, that in fact how to do blogging and site-building.

  • You actually make it seem so easy with your presentation but I in
    finding this matter to be really one thing which I feel I would never understand.
    It seems too complicated and very vast for me.
    I am taking a look forward for your subsequent post, I will attempt to get the dangle
    of it!

  • Ahaa, its nice dialogue about this post at this place at this webpage, I have read all
    that, so now me also commenting here.

  • Outstanding post however I was wondering if you could write a
    litte more on this subject? I'd be very thankful if you could elaborate a little bit further. Thanks!

  • Great article, totally what I needed.

  • Appreciate this post. Will try it out.

  • I do consider all of the concepts you've presented in your post. They're very convincing and will certainly work.
    Nonetheless, the posts are very short for novices. May
    just you please prolong them a bit from subsequent time?
    Thanks for the post.

  • My brother recommended I might like this blog. He was totally right.
    This post actually made my day. You can not imagine simply how much
    time I had spent for this information! Thanks!

  • This website definitely has all the info I wanted about this
    subject and didn't know who to ask.

  • These are in fact fantastic ideas in on the topic of blogging.
    You have touched some good factors here. Any way keep up wrinting.

  • Hello, this weekend is pleasant in favor of me, because this moment i am reading
    this enormous educational paragraph here at my residence.

  • Saved as a favorite, I really like your website!

  • Really good post. keep it up!

  • For the reason that the admin of this website is working,
    no doubt very shortly it will be well-known, due to its
    feature contents.

  • This is actually interesting, you are a very professional blogger.
    I’ve joined your rss feed and sit up for searching for more
    of your fantastic post.In addition, I have shared your website in my social networks!

  • I tend not to create a comment, however after looking at
    through a few of the responses on getting a this. with addEventListener and attachEvent - Andy
    Smith's Blog. I do have some questions for you if it's okay.
    Is it just me or do a few of the responses come across as if they are coming
    from brain dead folks? :-P And, if you are writing on additional online social sites, I'd like to follow everything fresh you have to post. Would you post a list of every one of your social networking pages like your linkedin profile, Facebook page or twitter feed?

  • This paragraph is really a fastidious one it helps new internet people,
    who are wishing for blogging.

  • What's up, every time i used to check weblog posts here in the early hours in the dawn, since i enjoy to find out more and more.

  • constantly i used to read smaller articles that
    also clear their motive, and that is also happening with this post which I
    am reading here.

  • You really make it seem so easy with your presentation but I find this topic to
    be really something that I think I would never understand.
    It seems too complicated and very broad for me.

    I am looking forward for your next post, I will try to get the hang of
    it!

  • Quality articles or reviews is the secret to
    be a focus for the viewers to pay a quick visit the site, that's what this site is providing.

  • Exercises for carpal tunnel Syndrome TreatmentMedian Mettle Sailplaning ExercisesTo do medial
    mettle sailing your wrist can speedily loosen up the muscles and help oneself easiness the
    painful sensation. In that respect are ergonomic calculator go aids designed prevent complications go on.

  • I got this site from my pal who told me concerning this web page and now this
    time I am visiting this web page and reading very informative posts at this
    time.

  • Link exchange is nothing else except it is only placing the other person's blog link on your page at appropriate place and other person will also do same in favor of you.

  • I have been surfing online greater than three hours as
    of late, yet I never found any fascinating article like yours.
    It's pretty price sufficient for me. In my opinion, if all webmasters and bloggers made excellent content as you did, the internet shall be a lot more helpful than ever before.

  • Fine way of explaining, and good piece of writing to take data concerning my presentation focus, which i
    am going to present in institution of higher education.

  • You should take part in a contest for one of the highest quality websites on the net.

    I'm going to highly recommend this site!

  • Your own article offers established necessary to myself.
    It’s really informative and you're simply naturally extremely experienced in this region. You have got opened up my personal eye to different views on this particular subject together with intriguing and strong written content.

  • I every time used to study post in news papers but now as I am a user of net thus from
    now I am using net for content, thanks to web.

  • Your own post features proven useful to myself. It’s extremely informative and
    you are clearly quite well-informed of this type. You possess exposed my
    own sight to be able to different opinion of this specific
    subject matter along with intriguing, notable and strong written content.

  • Panicat casada n�o pode, n�? � igual Panicat gorda, n�o combina , completou.
    ejercicios para bajar de peso

  • I am regular visitor, how are you everybody? This paragraph posted at this web site is
    truly fastidious.

  • She offers thermage CPT, Fraxel laser resurfacing,
    Smartlipo laser liposuction, optical maser plumping effect giving you that revitalised Appearance.

    We won't be is authoritative to protect your cervix area from the environmental causes of ageing peel.

  • You have absolutely highlighted an authentic dilemma here as,
    in actual fact I have in my little acne questionnaire blog

  • Loved your site and have now book marked your blog. Maybe you
    would like to learn more concerning my very own practical knowledge of linden method trichotillomania - you will
    discover more within my web site.

  • Pretty component to content. I just stumbled upon your site
    and in accession capital to claim that I acquire in fact loved account your weblog posts.
    Any way I will be subscribing on your augment and even I achievement you get right of entry to consistently
    quickly. reduce breast size

  • Howdy! I realize this is sort of off-topic however I needed to ask.
    Does building a well-established website such as yours require a large amount of work?
    I'm completely new to running a blog however I do write in my journal everyday. I'd like to
    start a blog so I can share my experience and thoughts online.

    Please let me know if you have any recommendations or tips
    for brand new aspiring bloggers. Appreciate it!

  • I enjoy what you guys are up too. This type of clever work
    and coverage! Keep up the fantastic works guys I've added you guys to my blogroll.

  • It's in fact very difficult in this full of activity life to listen news on Television, therefore I only use internet for that purpose, and take the most recent news.

  • Your own article has established necessary to me personally.

    It’s really helpful and you're simply naturally extremely experienced of this type. You get opened up our face to different opinion of this matter with intriguing, notable and reliable content.

  • Your current post offers verified beneficial to me personally.
    It’s very informative and you're certainly very well-informed in this field. You possess opened my own eyes in order to numerous thoughts about this particular matter along with intriguing and solid content material.

  • One-year postgraduate certification program in radiation therapy.

    Hence, holistic approach can cure ovarian cysts will depend upon the type of campaign, the
    next question is how long should it take to produce such reports?

    No so daft as you bend forward.

  • Marina Inn online pokiess has many locations throughout the mastered the
    Deal At that place were embers blowing across the
    route.

  • Each time you write a response to a discussion, it earns you 1 cent.
    Therefore in this tutorial I'm just going to be very basic and simple and teach you how to access the FPC channel and then let you loose, so to speak. Also, you do not have to worry about virus attacks.

  • The post features proven necessary to myself. It’s extremely
    helpful and you really are certainly quite experienced in this area.
    You have popped my face for you to varying thoughts about this subject matter using intriguing, notable and sound
    content.

  • This page certainly has all the information and facts I wanted concerning this subject and didn't know who to ask.

  • I like reading a post that will make men and women think.
    Also, thanks for allowing me to comment!

  • Write more, thats all I have to say. Literally, it seems as though you
    relied on the video to make your point. You obviously know what youre talking about, why throw away your intelligence
    on just posting videos to your weblog when you could be giving
    us something enlightening to read?

  • Good way of explaining, and fastidious piece of
    writing to get data concerning my presentation topic, which i am going to deliver in university.

  • Its like you read my thoughts! You appear to understand a lot approximately this, such
    as you wrote the e book in it or something.
    I think that you simply can do with some percent to force the message house a bit,
    however other than that, this is excellent blog. A fantastic read.
    I will certainly be back.

  • You could definitely see your enthusiasm in the work you
    write. The world hopes for even more passionate writers like you who aren't afraid to mention how they believe. All the time go after your heart.

  • I hardly drop remarks, but i did a few searching
    and wound up here getting a this. with addEventListener and
    attachEvent - Andy Smith's Blog. And I actually do have 2 questions for you if it's allright.
    Is it simply me or does it look as if like some of these responses appear like
    written by brain dead visitors? :-P And, if you are writing on
    additional online sites, I'd like to keep up with everything new you have to post. Would you make a list of the complete urls of all your community sites like your linkedin profile, Facebook page or twitter feed?

  • Good day! Do you know if they make any plugins to protect against hackers?
    I'm kinda paranoid about losing everything I've worked hard on.
    Any tips?

  • I was wondering if you ever thought of changing the layout of your website?
    Its very well written; I love what youve got to say.
    But maybe you could a little more in the way of content so people could connect with it
    better. Youve got an awful lot of text for only having
    1 or two images. Maybe you could space it out better?

  • I think this is one of the such a lot significant info for me.
    And i'm glad studying your article. But should statement on few normal issues, The web site taste is wonderful, the articles is in point of fact great : D. Excellent task, cheers

  • I love your blog.. very nice colors & theme. Did you design this website yourself
    or did you hire someone to do it for you? Plz respond as I'm looking to design my own blog and would like to find out where u got this from. cheers

  • This piece of writing is truly a good one it helps new net visitors, who are wishing for
    blogging.

  • I love what you guys are usually up too. This type of clever work and coverage!
    Keep up the good works guys I've incorporated you guys to my own blogroll.

  • Your current article features confirmed beneficial to myself.

    It’s very useful and you're simply obviously very well-informed of this type. You possess popped our eye to be able to varying views on this matter together with intriguing, notable and strong articles.

  • Your own report features verified necessary to us. It’s extremely helpful and
    you're simply naturally quite well-informed in this field. You have exposed my eye in order to different opinion of this specific matter with interesting and sound content material.

  • Way cool! Some very valid points! I appreciate you penning this write-up plus the rest of the
    website is very good.

  • Your current post features confirmed useful to
    me. It’s extremely educational and you really are obviously very well-informed in this region.

    You have popped my eye to be able to different
    views on this kind of subject along with intriguing, notable and solid articles.

  • Nefarious Rhinoceros - a in a body and resilient animal. he did not as rotund as the bloodless rhinoceros, but stilly stimulating - reaches the power 2-2, 2 m, lengths of up to 3, 15 m in height shoulders of 150-160 cm.

  • The report provides proven useful to us. It’s really helpful and you really are
    naturally quite experienced in this area.

    You have popped my eye in order to various opinion of this topic together with intriguing, notable and reliable content
    material.

  • It consists of a blend of proteins, vitamins,
    minerals, and other times masterbation lube to offend.

    They were also told to pay $8, 180 in restitution for Johnston's funeral and burial. Johnsonville Bratwurst, Italian Sausage or Italian Ground Sausage - $3.

  • The report features verified helpful to us. It’s
    really helpful and you really are certainly really educated in this field.
    You possess opened up my own face to be able to various views on this specific
    topic with intriguing and sound content material.

  • I am actually delighted to read this webpage posts which
    consists of lots of valuable data, thanks for providing these statistics.

  • Wow! Finally I got a website from where I can really obtain useful facts regarding my study and knowledge.

  • Excellent article. I definitely appreciate this website.
    Continue the good work!

  • Greetings from Ohio! I'm bored to death at work so I decided to browse your website on my iphone during lunch break. I enjoy the information you provide here and can't wait to
    take a look when I get home. I'm surprised at how fast your blog loaded on my cell phone .. I'm not even using WIFI, just 3G .
    . Anyhow, wonderful site!

  • Everyone loves what you guys are up too. Such clever work and coverage!
    Keep up the wonderful works guys I've incorporated you guys to my personal blogroll.

  • I know this if off topic but I'm looking into starting my own blog and was wondering what all is required to get set up? I'm assuming having a
    blog like yours would cost a pretty penny? I'm not very internet smart so I'm not 100% sure.
    Any tips or advice would be greatly appreciated.
    Cheers

  • I love your blog.. very nice colors & theme. Did you make this website yourself or did you
    hire someone to do it for you? Plz respond as I'm looking to construct my own blog and would like to know where u got this from. thanks a lot

Comments have been disabled for this content.