Reputation: 15138
I'm trying to use .hover
method of jquery
in a javascript class:
var test = {
init:function(){
$("#elm li").hover(test.showTitle(this), test.hideTitle());
},
showTitle:function(e){
...
},
hideTitle: function(){
...
}
};
$(document).ready(function() {
test.init();
});
but here this
refers to class itself and not to eventObject
.
How can I listen for events with jquery from a javascript class?
Upvotes: 0
Views: 45
Reputation: 6560
If you simply remove the parenthesis and the usage of the this
keyword, jQuery will call your functions with the required variables as expected within the context of the element.
var test = {
init:function(){
$("#elm li").hover(test.showTitle, test.hideTitle);
},
showTitle:function(e){
console.log(e)
console.log(this);
},
hideTitle: function(){
}
};
$(document).ready(function() {
test.init();
});
Upvotes: 2
Reputation: 4310
Wrap the call in an anonymous function that gives you access to e
.
#("elm li").hover(function(e) {
test.showTitle(e); //or this
}, function(e) {
test.hideTitle(e); //or this
});
Upvotes: 1
Reputation: 12815
You should be applying that to each element that is returned by your class query.
$("#elm li").each(function() {
var $self = $(this);
$self.hover(test.showTitle($self), test.hideTitle());
}
Upvotes: 1