Reputation: 2475
I am attaching a document key press event like
$(document).live("keypress",myObject.onDocumentKeyPress);
and my handler implementation is
onDocumentKeyPress:function(e){
if(e.keyCode == 13) { //Enter keycode
myobject.onColumnOptionClick(null,true);
}
}
,
Now in this function am getting e is not defined
.
How can pass event object to event handler?
I got a suggestion that
$(document).live("keypress",function(e){
myObject.onDocumentKeyPress(e);
});
but in this case I will find difficult to unbind that particular handler.
Please suggest me a way.
Upvotes: 0
Views: 726
Reputation:
This is fine:
$(document).on("keypress",function(e){
myObject.onDocumentKeyPress(e);
});
You said : but in this case I will find difficult to unbind that particular handler.
And for unbinding it, use namespace when attaching event handler:
$(document).on("keypress.something",function(e){
myObject.onDocumentKeyPress(e);
});
Now you can unbind the event handler with that namespace:
$(document).off("keypress.something");
.live()
is deprecated in version 1.7, and removed in version 1.9. Use .on()
instead.References:
.on()
- jQuery API DocumentationAs @adeneo said in comments, the event is always passed automagically:
$(function () {
var o = {
f: function (e) {
alert(e.keyCode);
}
}
$(document).on("keypress", o.f);
});
You can check the jsFiddle demo. So the problem is elsewhere which you get error e is not defined
. Try replacing your jQuery version with 1.7+
and use .on()
method.
Upvotes: 4
Reputation: 36393
var myobject = {
onDocumentKeyPress: function (e) {
console.log('Event ', e);
}
};
$(document).live('keypress', myobject.onDocumentKeyPress);
This will and does get e
as Event Object.
As NOX pointed out, the issue might be you using jQuery 1.9, in which live
is removed. Try replacing live
with on
.
Upvotes: 2