Reputation:
I have something wrong with the following code. I can't understand what is wrong with it.
function some(){
for (var i=0;i<....;i++)
{
var oneObject;
...some logic where this object is set
oneObject.watch(property,function(id, oldval, newval){
globalFunction(oneObject,id,newval);
return newval;
});
}
}
If I have for example three cycles and set three different objects I have the following result. Three different objects (for example oneObject can be equal some={},some.foo={}, some.boo={}
) are set. Every of them has its own watch handler (I change the object and the handler is called). The problem is that when globalFunction is called oneObject that is passed as argument is always equal to the last object of for loop.
I can't understand why it happers as for every new cycle I redeclare oneObject variable using var. Please, explain.
EDIT
Also I tried:
function some(){
for (var i=0;i<....;i++)
{
var oneObject;
...some logic where this object is set
oneObject.watch(property,function(id, oldval, newval){
(function(obj) {
globalFunction(obj,id,newval);
}(oneObject))
return newval;
});
}
}
Upvotes: 0
Views: 47
Reputation: 36592
Since oneObject
refers to an object, changing it will also change other references to that object. You can solve this with a closure.
(function(obj) {
globalFunction(obj,id,newval);
}(oneObject))
This way, each time you call globalFunction
it will receive a unique copy of oneObject
.
You need to create a closure for the entire reference to oneObject
:
(function(obj) {
obj.watch(property,function(id, oldval, newval){
globalFunction(obj,id,newval);
return newval;
});
}(oneObject));
(I'm curious what that return
is expected to do in a callback, but that's a separate issue.)
Upvotes: 2
Reputation: 826
I don't think that oneObject persists outside of the scope. You might try using an array of oneObjects so that your oneObject variable doesn't get re-assigned each iteration. It tends to be precarious to declare variables inside of a for loop.
Upvotes: 0
Reputation: 3984
It is a little hard to tell from the abstracted code you provided but this looks like a problem caused by using an asynchronous event-loop callback (i.e. the function in watch
). What typically happens in situations like this: The main loop sets up a callback. The value changes, triggering the event that is being listened to (i.e. the watch
). The callback is queued in the event-loop, which is different from the main executing loop. The callback doesn't get fired until the next open cycle, which might mean the main loop has been executing in the meantime, changing the value more.
It is a little hard to explain here, but here is a link to a wonderful video that will walk you through the details of what might be happening: https://www.youtube.com/watch?v=8aGhZQkoFbQ
Upvotes: 0