zero
zero

Reputation: 3084

Understanding JavaScript custom event listeners

I've been doing quite a bit of research (Google) on custom events, but I can't seem to find an answer to my question.

My question is as follows: in this example, I have divs inside of a div I'm sliding and wanted to make a custom event that is attached to all of the child divs so whenever a child div's offset left reaches a certain range the custom listener on that div will execute.

So really the question is: I'm I able to make truly custom event listeners on the same level as onchange, click, onmouseup etc. Which will listen for what I want them to listen for?

Upvotes: 0

Views: 1707

Answers (2)

Kevin B
Kevin B

Reputation: 95022

Yes, you can make truly custom events that work like onchange click onmouseup etc, however you have to write the listener code yourself based on existing events or methods.

In this case, you'll want to check the offset value in the move event, and when it reaches that target value, trigger the custom event.

Upvotes: 0

Ed Bayiates
Ed Bayiates

Reputation: 11210

I see you are using jQuery. It's very easy to define custom events with jQuery. I use a pattern like this:

// Constructor
function Colorbar() {
    this.events = $({});
    // (Whatever else is in the class)
}
colorbar = new Colorbar();

You can then listen for an event of any name:

colorbar.events.on("currentcolorchanged", function(e, cb, ncolor) {
    helper.doColorChanged(ncolor);
});

And trigger it:

this.events.triggerHandler("currentcolorchanged", [this, ncolor]);

If you are working with DOM objects, just cache the jQuery of the DOM object:

var $ele = $("#myElement");
$ele.on("myCustomEvent", function(e) {
    // Event handler
});
$ele.triggerHandler("myCustomEvent");

Upvotes: 1

Related Questions