How to emit events?

Hello!
I'm creating custom node and having a hard time understanding how to execute/trigger/emit custom event (with listener in js part) from editor (html part). Is that even possible?

The editor code runs in the browser. The Node-RED event emitter lives in the runtime as it is a node.js feature.

However, you can easily create a simple event handler in the browser. BUT it really depends what you are actually trying to achieve. Especially bearing in mind that some nodes isolate the scripts in the editor by wrapping them in an IIFE.

You can also find an example browser-based event handler in uibuilder's front-end library. The following is taken from Stack Overflow:

var class_test = function() {
   this.dispatcher = $({})
}

Class_test.prototype = {
   some_property: null,

    doSomething: function(msg) {
            this.some_property = msg
            this.dispatcher.trigger("somethingHappened")
    }
};

var test = new Class_test()

test.dispatcher.on('somethingHappened', function() {
    alert("Event")
})

test.doSomething('Example')

Thank you for reply!
In truth, i need to perform HTTP request while editing node properties. Maybe you could recommend better approach?

Hi @Daft11

this Stack Overflow answer outlines how you can do it: javascript - Send data on configuration - Stack Overflow

Essentially, you create an admin HTTP endpoint in your node's .js file that you can call from the node's .html file. They key things are to setup the paths properly on both sides.

Make sure you pick a path that is named for your node so it is unlikely to clash with any other admin end point.

1 Like

In addition to Nicks reply, you will find examples in any number of nodes and it is worth looking at the source code for those nodes as this is a great way to learn.

node-red-contrib-uibuilder contains a number of admin API endpoints for example.

There is one that looks up all of the url settings for all of the deployed uibuilder node instances to ensure that you cannot accidentally reuse the same name. Other ones allow the editor config panel get access to folders and files on the Node-RED server's uibRoot folder. Others allow management of npm packages.

Extremely grateful for the answer!

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