Understanding bind() to raise events
Posted: 10 Dec 2015 19:12
I'm relatively new to javascript, and have run across what looks like an odd use of bind() I'm trying to understand.
The pattern for raising events appears, from the documentation and few examples I can find online, to be triggered by binding to various objects:
The ...data.level object contains various properties, including 'value' as shown in the example code.
From my reading about bind(), I would've expected to see its first argument being something that would become the 'this' within 'level', even though 'level' is not a function.
It appears like using bind() this way is intended to give the bound anonymous function -- the 'this' argument -- access to the properties of 'level', and get executed every time 'level' gets assigned. At least, I presume that's the goal, since the point is to raise an event whenever something gets assigned to 'level'.
Is this a reasonable interpretation? Are folks familiar with this construct/pattern to raise events?
The pattern for raising events appears, from the documentation and few examples I can find online, to be triggered by binding to various objects:
Code: Select all
zway.devices[2].instances[1].SwitchBinary.data.level.bind(function() {
state = 'on';
if (this.value == '0')
state = 'off';
eventString = 'Device_2_Instance_1_' + state;
try {
// do interprocess stuff via, e.g., sockets
return;
} catch(err) {
debugPrint("Failed to execute script system call: " + err);
}
});
From my reading about bind(), I would've expected to see its first argument being something that would become the 'this' within 'level', even though 'level' is not a function.
It appears like using bind() this way is intended to give the bound anonymous function -- the 'this' argument -- access to the properties of 'level', and get executed every time 'level' gets assigned. At least, I presume that's the goal, since the point is to raise an event whenever something gets assigned to 'level'.
Is this a reasonable interpretation? Are folks familiar with this construct/pattern to raise events?