Logic Machine Forum
Custom events in JS - Printable Version

+- Logic Machine Forum (https://forum.logicmachine.net)
+-- Forum: LogicMachine eco-system (https://forum.logicmachine.net/forumdisplay.php?fid=1)
+--- Forum: Scripting (https://forum.logicmachine.net/forumdisplay.php?fid=8)
+--- Thread: Custom events in JS (/showthread.php?tid=1197)



Custom events in JS - buuuudzik - 29.01.2018

Hello,

I want to create some custom events in JS. I've found such solution:
Code:
var event = new CustomEvent(
    "newMessage",
    {
        detail: {
            message: "Hello World!",
            time: new Date(),
        },
        bubbles: true,
        cancelable: true
    }
);

document.getElementById("msgbox").dispatchEvent(event);
https://www.sitepoint.com/javascript-custom-events/

But to do this I must connect event to some nearly dummy selector but I know that currently there are such events:

Code:
.. grp.listen('6/0/54', function(obj, type) { ...

which not need any HTML selector. How to do something similar, e.g. generate event when plan changed for whole scripts?


RE: Custom events in JS - admin - 29.01.2018

grp.listen has its own store for listeners. If you want to create something custom you will have to create your own implementation. So it might be easier to attach custom events to $(window). As for plan change, there's already a 'showplan' event attached to document.body:
Code:
$(document.body).on('showplan', function(event, id) {
  console.log('new plan id is', id);
});



RE: Custom events in JS - buuuudzik - 29.01.2018

Very nice and I didn't know about this. Very nice and very thanks Smile

Can you eventually prepare some example how to do the smallest one custom event like grp.listen?


RE: Custom events in JS - admin - 01.02.2018

You can also attach custom events to a plain object via jQuery:
Code:
var myobj = $({});

myobj.on('myevent', function(event, p1, p2) {
  console.log(event, p1, p2);
});

myobj.trigger('myevent', [ 'param1', 'param2' ]);



RE: Custom events in JS - buuuudzik - 01.02.2018

SuperbWink