Bruno Ferreira
Bruno Ferreira

Reputation: 484

Define and trigger a custom event

I have the need to call a custom event on my DatatTble's cells. So, I have the following method:

(function ($) {
  $.fn.longClick = function (callback) {
    //event
  };
})(jQuery);

To make the binding, as a test, I do the following:

$("h1").longClick(function () {
  console.log('triggered');
});

I need to replace my click event:

$('#dtStatus').on('click', 'tbody td:not(:first-child)', function (e) {
  console.log('triggered');
});

With my longpress event.

$('#dtStatus').on('longClick', 'tbody td:not(:first-child)', function (e) {
  console.log('triggered');
});

The h1 longclick and td click event work, but the td longpress doesn't. Can some one tell me why I can't use my event like on('longClick')?

Thank you.

Upvotes: 0

Views: 71

Answers (1)

Vaidas
Vaidas

Reputation: 1503

I think you are mixing up functions with events. With $.fn.longClick you created a function that you already called successfully with $("h1").longClick(...).

Now, to use it like an event, you need to trigger it first. For example:

$('#dtStatus').click(function() {
    $(this).trigger("myEvent");
});

It triggers event with name myEvent on the item that was clicked. Then you can catch that event with:

$('#dtStatus').on("myEvent", function() {
    alert("myEvent called!");
});

You can read more about custom events in jQuery documentation.

Upvotes: 1

Related Questions