简体   繁体   English

jQuery事件回调和全局变量

[英]jQuery event callback and global variables

I am facing a strange behaviour that defies my understanding of closures and scope in JS. 我面临一个奇怪的行为,这违背了我对JS中的闭包和范围的理解。

Here is my code sample : 这是我的代码示例:

  var cta_container   = $("#call_to_action_container");
  var cta_div         = "<div>SOME VARYING HTML</div>";
  var ruler           = $('<div id="height_ruler"/>');
  var ctac_height;


  ruler.append(cta_div);
  cta_container.append(ruler);
  ctac_height = ruler.outerHeight();


  // If we already reached phase 3, we don't attach handlers again
  if (!this.reached_phase_3) {
    cta_upper.click(function(event) {
      console.log("Height during click callback : "+ ctac_height);
    });
  }
  this.reached_phase_3 = true;


  console.log("Height before click : "+ ctac_height);
  cta_upper.click();// Manually triggering the click
  console.log("Height after click : "+ ctac_height);

This is part of a Backbone's View's method. 这是骨干网视图方法的一部分。 Basically, I have a div I can toggle by clicking on it. 基本上,我有一个div我可以单击它来切换。 This div changes size over time. 这个div会随着时间改变大小。 I access its outerHeight as a global variable from the click event callback. 我从click事件回调outerHeightouterHeight作为全局变量进行访问。 But the value within the callback scope doesn't get updated, although the value within Backbone's View's method gets updated properly. 但是,尽管Backbone的View方法中的值已正确更新,但回调范围内的值并未更新。

For instance, on first click, this code might output : 例如,第一次单击时,此代码可能输出:

Height before click :            100
Height during click callback :   100
Height after click :             100

And then, after the div height has changed, I click again and get for instance : 然后,在div高度更改后,我再次单击并获得例如:

Height before click :            147
Height during click callback :   100
Height after click :             147

The value of the ctat_height variable gets updated within the method call setting up the callback, but not within the callback scope. ctat_height变量的值在设置回调的方法调用中更新,但不在回调范围内更新。

From what I know about closures, they don't copy global variables value within their scope, but access them via the scope chain. 根据我对闭包的了解,它们不会在其作用域内复制全局变量值,而是通过作用域链进行访问。 So how come ctat_height doesn't get updated properly? 那么,为什么ctat_height无法正确更新?

I am quite sure I can easily find a workaround to this issue, but this wouldn't help me understanding why this is not working. 我很确定我可以轻松找到解决此问题的方法,但这并不能帮助我理解为什么它不起作用。

If someone could explain to me why it acts like this, or point me to an appropriate resource, I would be very thankful! 如果有人可以向我解释为什么会这样,或者指出合适的资源,我将非常感激!

基于@ Kevin-b的答案,我找到了一个非常快速的解决方案,该解决方案是在View的范围内设置ctac_height变量( this.ctac_height而不是var ctac_height )。

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

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