简体   繁体   English

如何从匿名鼠标事件函数内部访问变量?

[英]How can I access a variable from inside an anonymous mouse-event function?

I'm trying to access the variable myvar from outside like so: 我试图像这样从外部访问变量myvar

$(document).mousemove(function(e){
    var myvar = winHeight() + scrollY() - e.pageY;
}); 
console.log(myvar);

But Chrome's javascript console keeps saying "Uncaught ReferenceError: myvar is not defined all-products:203 (anonymous function)" 但是Chrome的JavaScript控制台一直说“未捕获的ReferenceError:未定义myvar all-products:203(匿名函数)”

What am I doing wrong? 我究竟做错了什么? How do I access this variable outside this function? 如何在此函数之外访问此变量?

EDIT: I've realised that what I was attempting to do isn't realisable. 编辑:我已经意识到,我试图做的是无法实现的。 I have since changed my strategy completely and the code works fine now. 此后,我完全改变了策略,现在代码可以正常工作了。 (Thank you James and especially Vlad for your help!) (谢谢詹姆斯,尤其是弗拉德的帮助!)

You will need to move the variable to an outer scope which is accessible by both bits of code. 您将需要将变量移到外部范围,这两个代码位均可访问。

var myvar = -1;

$(document).mousemove(function(e){
    myvar = winHeight() + scrollY() - e.pageY;
}); 

console.log(myvar);

I think this is a job for javascript events. 我认为这是javascript事件的工作。 Basically you have a global variable which will be updated on mouse move. 基本上,您有一个全局变量,将在鼠标移动时进行更新。 After you update the variable you have to let other components know that the variable is ready for processing. 更新变量后,必须让其他组件知道该变量已准备好进行处理。

The code: 编码:

var myVar; // the global variable

// the function that will be caled when myVar has been changed
var myVarChangedHandler = function() {
    console.log('myVar variable has been changed: ' + myVar);
}

// bind the event to the above event handler
$('body').bind('MyVarChangedEvent', myVarChangedHandler);

// instal mouse move event handler on document
$(document).mousemove(function(e){
    myVar = winHeight() + scrollY() - e.pageY;
    $('body').trigger('MyVarChangedEvent');
}); 

UPDATE UPDATE

Removed the var keyword form the movemove event handler. 从movemove事件处理程序中删除了var关键字。

The code that depends on myVar should be put in the myVarChangedHandler function. 依赖于myVar的代码应放在myVarChangedHandler函数中。

I'll try to explain the best i can your code, the flaw in it and how you should be solving the problem using an analogy. 我将尽力解释您所能执行的代码的最佳内容,代码中的缺陷以及您应该如何使用类比来解决问题。 Let's take the following code (global variable corrected) 让我们采用以下代码(已纠正全局变量)

var myvar;
$(document).mousemove(function(e){
    myvar = winHeight() + scrollY() - e.pageY;
}); 
console.log(myvar);

Let's say you, the programmer, are a team leader in a web development department in some unnamed company and you have a list of tasks to be done in a day of work ( the tasks in our analogy is to update myvar everytime the mouse moves) You have at your disposal a repository ( var myvar ) and 2 developers: 假设您是一名程序员,是某个未命名公司的Web开发部门的团队负责人,并且您有一天要完成的任务清单(类推的任务是每次鼠标移动时都更新myvar )。您可以使用一个存储库( var myvar )和2个开发人员:

  • developer John ( function(e) { myVar = ... }; ) 开发人员John( function(e) { myVar = ... };
  • developer Ken ( console.log(myvar) ) 开发人员Ken( console.log(myvar)

09:00 You come to the office in the morning (user opens the page) 09:00您早上到办公室(用户打开页面)

09:05 You power up the server / repository 09:05您启动服务器/存储库

var myvar;

09:10 You tell John: John, please do this tasks and everytime you complete each task uploaded it to the repository, and go home after your hours are finished 09:10您告诉John:John,请执行此任务,每次完成每个任务后,将其上传到存储库,并在工作时间结束后回家

$(document).mousemove(function(e){
    myvar = winHeight() + scrollY() - e.pageY;
});         

09:11 You tell Ken: Ken, please test the code in the repository right now and go home after you have finished testing 09:11您告诉Ken:Ken,请立即测试存储库中的代码,并在完成测试后返回

console.log(myvar);

(at this time, Ken sees that the repository is empty and goes home - that's because John didn't had time to solve even on task in a minute so Ken has nothing to test) (这时,Ken看到存储库已空,可以回家了-这是因为John没时间在一分钟内完成任务,所以Ken没什么可测试的)

09:12 You go home 09:12你回家

At 09:12 there's only John at the office doing the tasks, You and Ken have left home because you don't have anything else to do. 在09:12,只有约翰在办公室里执行任务,您和Ken离开家了,因为您无事可做。 This also happens to your code. 您的代码也会发生这种情况。 You output the value of myvar but you haven't even moved the mouse so, of course, the value is undefined 您输出了myvar的值,但您甚至都没有移动鼠标,因此,该值是undefined

To solve this we add some modifications: 为了解决这个问题,我们添加了一些修改:

09:00 You come to the office in the morning 09:00您早上到办公室

09:05 You power up the server (repository) 09:05您打开服务器(存储库)的电源

09:10 You tell John: 09:10你告诉约翰:

John, please do this tasks and everytime you complete each task
uploaded it to the repository and tell Ken to test the code.
Go home after you have finished

09:11 You tell Ken: 09:11你告诉肯:

Ken, each time John tells you that he has completed a task,
fetch the code from the repository and test it.
Go home after he has finished

09:12 You go home 09:12你回家

at 09:12 both John and Ken are at the office doing their job. 约翰和肯在09:12都在办公室工作。

In the above case ken is myVarChangedHandler = function() {...}; 在上述情况下,ken是myVarChangedHandler = function() {...};

When John tells Ken that he completed the task an actual event occurs (the telling), when Ken acknowleges John signal he starts testing (Ken is the event handler) 当John告诉Ken他完成了任务时,就会发生实际事件(告诉),当Ken确认John发出信号表示他开始测试时(Ken是事件处理程序)

This is how event driven architecture in javascript works. 这就是javascript中事件驱动架构的工作方式。 I would advise you to ditch jquery, mootools, etc... and start learning the core concepts and the basics. 我建议您放弃jquery,mootools等...,并开始学习核心概念和基础知识。 Reinvent the wheel a few times then go back to jquery. 重新创建轮子几次,然后返回到jquery。 I hope i explained enough for you to understand. 我希望我能解释得足够让您理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM