Get NodeID from inside OnEditPrepare

I have a use-case where I need to get a Node's ID from inside OnEditPrepare in the Node's HTML frontend code.

I figured out a way to do it but it seems clunky and am wondering if there is something built-in I can access or is there a better way to do it.

My method was to create a small script to load into custom nodes:
/resources/MyCustomNode/GetNodeID.js

//
// Add this to any node where you want access to the NodeID
// from within the NodeRed HTML code like inside OnEditPrepare
//
// window.myNodeID
//

if (!window.myNodeID) {
    window.myNodeID = null;
    // Event listener for selection changes in the Node-RED workspace
    RED.events.on('view:selection-changed', function(event) {
        if (event.nodes && event.nodes.length > 0) {
            window.myNodeID = event.nodes[0].id;
        } else {
            window.myNodeID = null;
        }
    });
}

And then load and access it in my Custom Node as such...

<script src="/resources/MyCustomNode/GetNodeID.js"></script>
<script type="text/javascript">

    RED.nodes.registerType('MyCustomNode',{
        category: 'SomeCategory',
        color: '#FDD0A2',
        inputs:1,
        outputs:1,
        icon: 'font-awesome/fa-arrow-right',
        align: 'right',
        label: ()=> { return this.nodeLabel||'MyCustomNode' },
        oneditprepare: ()=>{ 
                console.log('My Node ID: ', window.myNodeID);
            }
        }
    });

I looked for a while but couldn't find anything.

Have you tried inspecting this.id in your oneditprepare function?

When I inspect "this" there is no parameter called "id".

        oneditprepare: ()=>{ console.log(this); }

Unless I'm doing something wrong, I don't see it.

what about now?

oneditprepare: function() {
   console.log(this.id);
}

It returns

undefined

I must be doing something wrong but not sure what.

Ok. I see now. Changed it function() and it works.

Thanks. Much easier.

Yup - do you want to know why - or do you already know why that is?

In short, arrow functions do not bind their own this, for node-red nodes, we need the "correct" this.

https://www.codementor.io/@dariogarciamoya/understanding-this-in-javascript-with-arrow-functions-gcpjwfyuc

Nope not sure exactly why... guessing it has to do with scoping.

Thanks for the explanation

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.