简体   繁体   中英

jQuery event callback and global variables

I am facing a strange behaviour that defies my understanding of closures and scope in 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. This div changes size over time. I access its outerHeight as a global variable from the click event callback. But the value within the callback scope doesn't get updated, although the value within Backbone's View's method gets updated properly.

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 :

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.

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?

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 )。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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