简体   繁体   中英

jquery event listening, non-standard events

I'm attempting to build a way for my selectors to 'listen' to 'global' events that are beyond the typical 'click' 'change' 'submit' etc. I've explored the various 'eventmanagers' that I could find, and they're all still designed for forms. Is there any way to do something like this for non-standard (ie custom) events? The goal is to have selectors subscribe to an event, and then be able to trigger it in one place and it will raise it for everything subscribed to it.

Inserting example for demonstration.

 return this.each(function () {
  $(this).live('ON_CONTENT_CHANGING', function (e) {
   $(this).block({
    overlayCSS: { opacity: 1, color: '#000' },
    timeout: 800
   });

   e.preventDefault();
  });

  $(this).live('ON_CONTENT_CHANGED', function (e) {
   $(this).sliding();
   $(this).unblock();

   e.preventDefault();
  });

// rest of plugin...

$("*").trigger('ON_CONTENT_CHANGING');

This is built into jQuery, for example:

$(".button").bind("myEvent", function() {
  alert("myEvent fired on " + this.id);
});

Trigger by:

$("*").trigger("myEvent");

Or on a specific element (or any selector, like everything else jQuery):

$("#myButton").trigger("myEvent");

This uses .bind() and .trigger() . As Jacob points out in comments, you can also bind with .live() to custom events in 1.4+, like this:

$(".button").live("myEvent", function() {
  alert("myEvent fired on " + this.id);
});

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