简体   繁体   中英

add event to Jquery Plugin

I have a JQuery plugin and I want to add some event to it. Any help, tips, or tutorial?

As I understand correctly If you have some kind of button that close the popup and you need a function that is triggered after close.

(function($) {
  $.fn.somePlugin = function(options) {
    // do some stuff with popup
    $('#closeButton').click(function(e) {
      //close popup
      if (options.onAfterClose !== undefined) {
         options.onAfterClose(e);
      }
    });
  };
})(jQuery);

it just pass the event from click event.

$('#someId').somePlugin({
    onAfterClose: function(e) {
        alert('after close');
    }
});

In your jquery plugin, the first thing you will have to do is trigger your custom event somewhere in your plugin code:

$("#someElement").trigger("someSpecialEvent");

You can also pass data inside of your trigger function if you want.

$("#someElement").trigger("someSpecialEvent", "this does not need to be a string");

Next, create an event handler somewhere else in your plugin code for your custom event:

$("#someElement").bind("someSpecialEvent", function(event, data) {
    //If you had passed anything in your trigger function, you can grab it using the second parameter in the callback function.
});

You can then allow a user to pass a callback function as an option like this:

$("#sampleElement").myPlugin({ 
    someEvent: function() {
        //user logic
    }
});

Finally, inside of your plugin code, you can call the user's function a few different ways. An example would be:

$.fn.samplePlugin = function(options) {
        options = $.extend({}, $.fn.samplePlugin.options, options);
        $("sampleElement").bind("specialEvent", function() {
             options.someEvent.call();
        });
 }

jQuery docs has everything about triggering an event

Any element that has been attached to an event using $.bind() will be notified that the event had been triggered and execute its code.

Example:

$(document).trigger('my.event');

jQuery supports 'namespaced' events, so you can name the event something like mypluginName.eventName to make sure no other plugin interferes with you events ;)

Simple and clean, although be careful, docs state that:

Although .trigger() simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally-occurring event.

Nice day

$("#someElement").on("someSpecialEvent", function(event) {

});

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