Rizo
Rizo

Reputation: 54

Prototype - addEventListener Click - JavaScript

I need some help with the below code that I wrote, I need to return the element on click but for some reason it sends back the Window object and not the HTMLElement.

HTML

<div id="myDiv">Click me!</div>

JavaScript

   function myP(selector) {
        if (!(this instanceof myP)) {
            return new myP(selector);
        }

        this.elem = document.querySelector(selector);
    }        

    myP.prototype = {
        click : function(objF){
            this.elem.addEventListener("click", function(){
                objF();
                console.log(this); //Returns the Element ( <div id="myDiv"> )
                return this; // Doesn't work
            }, false);
        }
    }

    myP("#myDiv").click(function(){
        console.log(this); // Returns [object Window]

        // I want to return: ( <div id="myDiv"> ) Element here

    });

Thanks

Upvotes: 0

Views: 315

Answers (1)

Rayon
Rayon

Reputation: 36609

Use .call(EXPECTED_CONTEXT) to pass EXPECTED_CONTEXT as this in called function.

Try this:

function myP(selector) {
     if (!(this instanceof myP)) {
       return new myP(selector);
     }

     this.elem = document.querySelector(selector);
   }

   myP.prototype = {
     click: function(objF) {
       this.elem.addEventListener("click", function() {
         objF.call(this);
         return this;
       }, false);
     }
   }

   myP("#myDiv").click(function() {
     console.log(this);
   });
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<div id="myDiv">Click me!</div>

Upvotes: 1

Related Questions