对象中的 Javascript 键盘事件
我用一种简单的方式让我的键盘工作:
rightPressed = false;
onKeyDown = function(pressEvent) {
if (pressEvent.keyCode == 39) rightPressed = true;
}
onKeyUp = function(pressEvent) {
if (pressEvent.keyCode == 39) rightPressed = false;
}
$(document).keydown(onKeyDown);
$(document).keyup(onKeyUp);
并且它工作了。然后我尝试将其全部放入一个类中:
function Tkeyboard(){
this.rightPressed = false;
this.onKeyDown = function(pressEvent) {
if (pressEvent.keyCode == 39) { this.rightPressed = true; alert("boom!"); }
}
this.onKeyUp = function(pressEvent) {
if (pressEvent.keyCode == 39) { this.rightPressed = false; }
}
$(document).keydown(this.onKeyDown);
$(document).keyup(this.onKeyUp);
}
在初始化中我创建了一个对象:
keys = new Tkeyboard;
在主循环中我放置了操作:
if ( keys.rightPressed ) { rx+=1;}
现在它失败了。问题的有趣部分是调用了警报(“boom!”),因此变量也应该被修改......
我将不胜感激任何想法。
I got my keyboard working in a simple way:
rightPressed = false;
onKeyDown = function(pressEvent) {
if (pressEvent.keyCode == 39) rightPressed = true;
}
onKeyUp = function(pressEvent) {
if (pressEvent.keyCode == 39) rightPressed = false;
}
$(document).keydown(onKeyDown);
$(document).keyup(onKeyUp);
And it worked. Then i tried to put it all in a class:
function Tkeyboard(){
this.rightPressed = false;
this.onKeyDown = function(pressEvent) {
if (pressEvent.keyCode == 39) { this.rightPressed = true; alert("boom!"); }
}
this.onKeyUp = function(pressEvent) {
if (pressEvent.keyCode == 39) { this.rightPressed = false; }
}
$(document).keydown(this.onKeyDown);
$(document).keyup(this.onKeyUp);
}
In initialization I created an object:
keys = new Tkeyboard;
In main loop i put action:
if ( keys.rightPressed ) { rx+=1;}
And now it fails. The interesting part of the problem is that alert("boom!") is called, so variable should get modified too...
I would be grateful for any ideas.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当实际运行时, keydown/up 回调将失去其原始范围。您需要将回调绑定到
this
。在原型框架中,您可以这样做:它应该与jQuery。
如果您需要了解如何构建完整的键盘类,请查看 我的那个写道。
The keydown/up callback loses its original scope when the it is actually run. You'll need to bind the callback to
this
. In the Prototype Framework, you would do this:It should be similar in jQuery.
If you need an idea of how to build a full fledged keyboard class, check out the one I wrote.
在 jQuery 中的事件处理程序中(以及在 DOM 事件中),
this< /code> 指订阅事件的元素(示例中的
document
)。如果您想引用原始对象,请使用闭包。In an event handler in jQuery (and in DOM events),
this
refers to the element the event is subscribed on (document
in the sample). Use a closure if you want to refer to the original object.this
设置为调用事件处理程序的 DOM 元素(在本例中为document
)。一般来说,this
不会绑定到 javascript 中的对象:一种常用的解决方法是将
this
绑定到包装函数:或者您可以使用闭包:
this
is set to the DOM element (in this casedocument
) from which the event handler is called. In general,this
is not bound to the object in javascript:One commonly used workaround is to bind
this
to a wrapper function:Or you could use closures:
你可以启动新功能它会起作用
you can initiate new function it will work