Skip to content Skip to sidebar Skip to footer

What Exactly Acts As A Trigger For A Custom Event In Javascript

I've been reading about custom events and looked at some examples. Perhaps I am misunderstanding what custom events are and how they are triggered and would appreciate some help. E

Solution 1:

Custom events are not like DOM events, they don't fire because some interaction happened in the browser. They happen when the person who writes the code decides for them to happen. You have to explicitly trigger custom event when you need one.

For example, you might have function like

functionupdateBackground (element, color) {
  elmenet.css('background-color', color);
  // element has to be an object that has `trigger` function on its prototype// like jQuery wrapped element, for example
  element.trigger('updated-background', color);
}

Then every time this code is executed you'll have 'updated-background' fired in context of this element.

UPD.

Using browser options a user can change font size, background colours etc, ie apply a new theme. As far as I know there are no native events within javascript to deal with these so I would need to create a custom event within my script. What I am trying to ask is how to you find out when a custom event takes place?

You find out because you create them. You are correct (to my knowledge) that there are no DOM events fired when user changes font-size / default body background etc. You could poll for body and fire custom event when you detect a change, as you said.

Solution 2:

In JavaScript, a custom event is simply a message, broadcast to all event listeners, that says, "Attention everyone: event X just happened!" Any listener that cares about that event can then run some function.

However, your custom event still needs to be fired somehow. Custom events aren't fired unless, somewhere in your code, you call .dispatchEvent (or .trigger, in jQuery). Your program must decide when it is time to fire the event. If the browser doesn't natively fire an event that you can use as a cue for your own custom event, then often polling is the only way to know when to fire the event.

The bottom line here is events are just messages. It's up to you and the code you write to decide when to fire them.

Post a Comment for "What Exactly Acts As A Trigger For A Custom Event In Javascript"