Search code examples
javascripthtmlnode-red

How to add chips/tags to a node's properties in Node-RED


I'm creating a Discord node in Node-RED, and want to give the node options as to which Discord events it will subscribe to. I'm currently attempting to use Chips from the MaterializeCSS library (https://materializecss.com/chips.html).

Following the examples on the Materialize page, here's my current property type:

<script type="text/javascript">
    RED.nodes.registerType('discordEvents', {
        category: 'config',
        defaults: {
            name: {value:"", required: true},
            events: {value:"", required: true},
        },
        exportable: false,
        label: function() {
            return this.name;
        }
    });
</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script type="application/javascript">
    $('.chips-autocomplete').chips({
        autocompleteOptions: {
            data: {
                'message':null,
                'ready':null
            },
            limit: Infinity,
            minLength: 1
        }
    });
</script>
<script type="text/x-red" data-template-name="discordEvents">
    <div class="form-row">
        <label for="node-config-input-name"><i class="icon-tag"></i> Name</label>
        <input type="text" id="node-config-input-name">
    </div>
    <div class="form-row">
        <label for="node-config-input-events"><i class="icon-tag"></i> Events</label>
        <div class="chips chips-autocomplete" id="node-config-input-events></div>
    </div>
</script>

The problem is when I load the library into the script, the Node-RED editor disappears, and if I check the console, I see an error "[node-red/discordEvents] TypeError: $(...).chips is not a function"


Solution

  • You can not add script tags like that in the node's html file. You need to dynamically load them as part of the node's oneditprepare function.

    You can look at the node-red-node-geofence node for an example.

    This uses the jquery $.getScript() function to load the script.