Philipp Spiess
Philipp Spiess

Reputation: 3271

Javascript Mootools click event and his caller?

I have this little script:

var moolang = new Class({
    initialize: function(element) { 

        this.el = $(element);
        this.el.addEvent('click', this.popup);  

    },

    popup: function()
    {
        //this.id = the id of the element.
    }
});

And I want to know "this" in the popup function, but if I try something like alert(this.el.id) it says there is no this.el.

Is there a way to know which class adds the event?

Upvotes: 0

Views: 461

Answers (1)

Josiah Ruddell
Josiah Ruddell

Reputation: 29831

Change the attach event so the callee has the proper context. Otherwise the context of an event listener will be the target element.

// Change this line
this.el.addEvent('click', this.popup);
//To this
this.el.addEvent('click', this.popup.bind(this)); // popup->this == this

jsfiddle here See mootools documentation. Binding the context of a function.

Upvotes: 5

Related Questions