Using functions in oneditprepare and oneditsave

I am re-factoring a couple of custom nodes and running into the limits of my understanding of JavaScript or the structure of Node-RED (or possibly both). I have large blocks of code that I use in several places in both the oneditprepare and oneditsave functions. I would like to put that code in a separate function called from both, but I have not figured out how to do it in the .html file. I have tried putting the function definition both inside and outside the RED.nodes.registerType section, but invoking it never seems to do anything. I must be missing something simple, but not so simple that I can find it by trial and error. I would appreciate any help.

This should do what you intend to do:

<script>
    function whatever() {
        console.log("whatever");
    }

    RED.nodes.registerType("whatever-node", {
        oneditprepare: function() {
            whatever();
        }
    })
</script>

Hi Mike,

If you care to check the uibuilder code, there are some good examples of this.

This node has a fairly simple example: node-red-contrib-uibuilder/editor.js at main · TotallyInformation/node-red-contrib-uibuilder (github.com)

The main uibuilder node is a lot more complex and has many functions: node-red-contrib-uibuilder/editor.js at main · TotallyInformation/node-red-contrib-uibuilder (github.com)

NB: For convenience, I have a workflow that splits each node's html file into multiple parts. A Gulp watch process sticks them back together as I save. That's why the files shared are a bare js file.

Thanks. I swear that was the first or second thing I tried. No clue why it didn't work, except possibly syntax error. Knowing it should work was a big help, and I'm now almost where I want to be.

Thanks for the link, Julian. When it was part of my job, I hated reading other people's code, even when I knew the language. Now, I've learned almost enough JS/jQuery/html/css to begin to enjoy the process. BTW, passing this as an argument is a nice trick than I plan to use in future.

1 Like

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