Understanding bind() to raise events

Discussions about RaZberry - Z-Wave board for Raspberry computer
Post Reply
markolbert
Posts: 64
Joined: 16 Oct 2014 06:09

Understanding bind() to raise events

Post by markolbert »

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:

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);
        }
    });
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?
User avatar
PoltoS
Posts: 7649
Joined: 26 Jan 2011 19:36

Re: Understanding bind() to raise events

Post by PoltoS »

this refers to the item you bind on. this.value is the value. For SwitchBinary it should be true/false, not '0'

There are many examples in the automation/modules/ZWave/index.js and others
Post Reply