简体   繁体   中英

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM