Results 1 to 2 of 2

Thread: Passing 'this' to an anonymous function in an event listener

  1. #1
    Join Date
    Jun 2010
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Passing 'this' to an anonymous function in an event listener

    Hello!

    I'm working with nested functions and trying to pass a 'this' value to an anonymous being used in an assignment for an event listener. Here's the basics of my code:

    Code:
    <div id='abc'></div>
    <script type='text/javascript'>
    var abc = function () {
        this.myFunction = function() {
            var myObj
            myObj = document.createElement("input");
            myObj.setAttribute("type", "button");
            myObj.setAttribute("value", "Click Me");
            myObj.addEventListener("click", function () {
                this.doDing();
            }, false);
            document.getElementById('abc').appendChild(myObj);
        }
        this.doDing = function () { alert('ding'); }
    }
    var myInstance = new abc();
    myInstance.myFunction();
    </script>
    So, this should plop a button inside our DIV and when clicked I'd like it to run the alert-ding; unfortunately it seems to want to run the function as defined under the buttons object.

    Any suggestions?

    Thanks!

  2. #2
    Join Date
    Dec 2008
    Location
    Portsmouth, UK
    Posts
    1,775
    Thanks
    2
    Thanked 411 Times in 406 Posts

    Default

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    
    <head>
      <title></title>
    </head>
    
    <body>
    <div id='abc'></div>
    <script type='text/javascript'>
    var abc = function () {
        this.myFunction = function() {
            var myObj,oop=this;
            myObj = document.createElement("input");
            myObj.setAttribute("type", "button");
            myObj.setAttribute("value", "Click Me");
            myObj.addEventListener("click", function () {
                oop.doDing();
            }, false);
            document.getElementById('abc').appendChild(myObj);
        }
        this.doDing = function () { alert('ding'); }
    }
    var myInstance = new abc();
    myInstance.myFunction();
    </script>
    </body>
    
    </html>
    Vic
    God Loves You and will never love you less.
    http://www.vicsjavascripts.org/Home.htm
    If my post has been useful please donate to http://www.operationsmile.org.uk/

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •