Arvin Flores
Arvin Flores

Reputation: 487

How to create custom events and call them using jQuery's .on()?

I'm trying to write a small library in jQuery and I'd like to add some lifecycle events. I understand that I have to return this; at the end to continue chaining.

Mockup of my library so far:

(function($))
  $.fn.myLibrary = function(){

    // some code here
    return this;

  }
)(jQuery)

This is what I'd like the end result to be:

$('#selector').myLibrary({
    // some options
})
.on('myLibrary-deleting', function(){
    // some code
});

I'm not sure if this question is phrased correctly but how do I extend jQuery's on function?

Upvotes: 1

Views: 3823

Answers (1)

Alexey Soshin
Alexey Soshin

Reputation: 17711

You don't need to extend .on() function. Simply trigger your custom even when you need to:

$(this).trigger('myLibrary-deleting')

And .on will keep working.

https://learn.jquery.com/events/introduction-to-custom-events/

Upvotes: 2

Related Questions