This forum uses cookies
This forum makes use of cookies to store your login information if you are registered, and your last visit if you are not. Cookies are small text documents stored on your computer; the cookies set by this forum can only be used on this website and pose no security risk. Cookies on this forum also track the specific topics you have read and when you last read them. Please confirm that you accept these cookies being set.

Custom events in JS
#1
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?
Reply
#2
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);
});
Reply
#3
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?
Reply
#4
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' ]);
Reply
#5
SuperbWink
Reply


Forum Jump: