The popover construction happens only once, during the first click event, because you cannot reconstruct a popover without destroying the old one.
So in your case :
"Count is " + a
, you construct the popover callback from thea
variable with the current value of a. Because you are 'recreating'a
at each click, the reference used will be the one of the firsta
variable created (during the first click). This reference will be lose once you'll be out the event function, so you won't be able to update it and only the first value will be used in the callback."Count is " + i
, you construct the popover callback using the global variablei
which will be available wherever and whenever you want, so you can modify it.
Obviously the #field2
will show the current value because you're using the current a
variable and not the old one from the first click.
To understand a bit more :
- First click : i = 1, a = 1. You're sending
a
, which could be seen asa1
(first a) to the callback function). Then you go out the event function, so thea
variable is destroyed BUT 'its memory' (what it was pointing in fact, everything is reference in javascript), so in memory you still have something likea0 -> 1
which is used in the callback. - Second click : i = 2, a = 2. You're NOT sending
a
to the popover constructor because you've already created the popover, so it is stilla0
which is used in the callback function. Then you go out the event function, and now thea
variable is pointing to its value. - Third click : Same as second, and etc.