views:

135

answers:

1

Hi,

I have a javascript object which has some defined variables and attaches some event handlers. I'd like the event handlers to have access to the defined variables. Is there a way to do that ? The event-handlers are within their own local scope so don't have access to the object variables. Is there a way to pass them in without using global variables ?

I have an idea that closures would solves this but I'm not sure how.

the code below will print the object name when the page loads but when you click on the map dom object it will say name is undefined.

All help much appreciated.

Colm

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Map Test</title>
        <meta charset="utf-8" />
        <script type="text/javascript">
            window.onload = function() {
                var e = new EvtTest();
                e.printName();
                e.attachEvents();
            };

            function EvtTest() {
                this.name = "EvtTest";
            }

            EvtTest.prototype.name = null;

            EvtTest.prototype.attachEvents = function () {
                var map = document.getElementById("map");
                map.addEventListener ('click', this.evtHandler, false);
            };

            EvtTest.prototype.printName = function () {
                console.log ("This Name : " + this.name);
            };

            EvtTest.prototype.evtHandler = function (e) {
                e.preventDefault();
                console.log ("Name : " + this.name);
            };
        </script>
        <style type="text/css">
            html, body {
                height:100%;
                width:100%;
                margin: 0;
                background-color:red;
            }
            #map {
                height: 300px;
                width: 300px;
                background-color:yellow;
            }
        </style>
    </head>

    <body>
        <div id="map"></div>

    </body>
</html>
+1  A: 

A little bit of fiddling:

EvtTest.prototype.attachEvents = function () {
    var that = this;
    var map = document.getElementById("map");

    map.addEventListener ('click', function () {
        that.evtHandler();
    }, false);
};

Now this inside evtHandler references the object you expected.

Matt
Excellent - that worked nicely. Thanks.
Protos