Nilzone-
Nilzone-

Reputation: 2786

Event handling on jQuery this

function Car(id) {
    var $this = this;

    this.init = function() {
        this.el = document.getElementById(id);
        $(this).on('keypress', function(e){
            alert(e.target);
        });
    }
}

The alert never happens. If I change $(this) to #hero. It works. I can't see why.

$(document).ready(function(){
    var hero = new Car("hero");
    hero.init();
});

Upvotes: 0

Views: 80

Answers (2)

adeneo
adeneo

Reputation: 318182

The element is obviously this.el, while this is the parent init() function :

function Car(id) {
    var $this = this; // you never use this ?

    this.init = function() {
        this.el = document.getElementById(id); // you set it to this.el
        $(this.el).on('keypress', function(e){ // so you should use that for the
            alert(e.target);                   // event handler as well
        });
    }
}

$(document).ready(function(){
    var hero = new Car("hero");
    hero.init();
});

FIDDLE

Of course, this would be more jQuery'ish:

this.init = function() {
    $('#' + id).on('keypress', function(e) {
        alert(e.target);                   
    });
}

Upvotes: 3

sudhansu63
sudhansu63

Reputation: 6180

Try this. You are bing the event to the function, bind it to the element.

function Car(id) {
    var $this = this;

    this.init = function() {
        this.el = document.getElementById(id);
        $(this.el).on('keypress', function(e){  //changed in this line
            alert(e.target);
        });
    }
}

Upvotes: 0

Related Questions