Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Using object method as event handler in javascript

Options
  • 06-08-2011 2:25pm
    #1
    Registered Users Posts: 377 ✭✭


    I have an object like so
    function Foo() {
        var site = 'boards';
    }
    
    Foo.prototype.HandleClick = function(e) {
        alert(this.site); // Doesn't work
    }
    
    var foo = new Foo();
    
    ...
    ...
    ...
    <a href='#' onClick='foo.HandleClick()'>Press me</a>
    
    In the click handler, the variable 'this.site' is invalid because 'this' refers to the <a> anchor and not the Foo object. Is there a way around this or do I just have to set the click handler to a global function and call the object from that, like so -
    function doClick(e) {
        foo.HandleClick(e);
    }
    <a href='#' onClick='doClick()'>Press me</a>
    

    It just seems a bit messy to do it that way.


Comments

  • Registered Users Posts: 255 ✭✭boblong


    [HTML]
    <html>
    <script>
    function Foo() {
    this.site = 'boards';
    }

    Foo.prototype.HandleClick = function(e) {
    alert(this.site); // Doesn't work
    }

    var foo = new Foo();
    </script>

    <a href='#' onClick='foo.HandleClick()'>Press me</a>
    [/HTML]

    ;)

    FYI it's generally good practice to separate logic from presentation as a general rule. For example I might refactor the above as:

    [HTML]
    <html>

    <a id="thelink" href='#'>Press me</a>

    <script>
    function Foo() {
    this.site = 'boards';
    }

    Foo.prototype.HandleClick = function(e) {
    alert(this.site); // Doesn't work
    }

    var foo = new Foo();

    document.getElementById("thelink").addEventListener('click', function(thing) {
    foo.HandleClick();
    });

    </script>
    </html>

    [/HTML]


Advertisement