sergej.shirokov пишет:Also, I don't see how the following is "more safe" - it HAVE to be the same unit, right?
I havent seen your code, but common practice is to add listener in loop, something like that
for (var i = 0; i < units.length; i++) {
unit = units[i];
unit.addListener('changeMessageParams', function handleChangeMessageParams () {
console.log(unit);
});
}
The output of this example in my case - one same unit for different events
cg {$$hash: "28-0", $$user_dataFlags: 1048577, _id: 11996104, $$user_name: "TestObject"…}
cg {$$hash: "28-0", $$user_dataFlags: 1048577, _id: 11996104, $$user_name: "TestObject"…}
cg {$$hash: "28-0", $$user_dataFlags: 1048577, _id: 11996104, $$user_name: "TestObject"…}
cg {$$hash: "28-0", $$user_dataFlags: 1048577, _id: 11996104, $$user_name: "TestObject"…}
Its the way JS works - it binds function to be called (handleChangeMessageParams), not a data inside it.
So when event triggers, handleChangeMessageParams calls and try to operate with unit variable. Since its not declared in function scope - it will be used from parent scope, where it is equal to last element of units array. To prevent this problem any kind of binding should be used.
Using event.target() makes handling event more comfortable - you'll always be able to get item for which event was triggered
Hope this helps
PS once again, i havent seen your code, and maybe you'll never face such a problem, i just noticed potential hole in your example. But event.getTarget() (and whole event object) can be very usefull when dealing with events, so i decided to tell you about it