Reputation: 2786
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
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();
});
Of course, this would be more jQuery'ish:
this.init = function() {
$('#' + id).on('keypress', function(e) {
alert(e.target);
});
}
Upvotes: 3
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