Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.
Hi all, please see this major site announcement: https://www.boards.ie/discussion/2058427594/boards-ie-2026

Using object method as event handler in javascript

  • 06-08-2011 01:25PM
    #1
    Registered Users, Registered Users 2 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, Registered Users 2 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