Custom event in jQuery that isn't bound to a DOM element?

前端 未结 7 1047
迷失自我
迷失自我 2020-12-12 20:28

I\'m curious if its possible to create a custom event in jQuery that isn\'t bound to a DOM element.

I greatly prefer jQuery to YUI but there is one thing in YUI that

相关标签:
7条回答
  • 2020-12-12 21:27

    You can still arbitrarily trigger and respond to events using jQuery, even if you don't know what element to attach them to. Just create a "receiver" element in your document, to which you can bind all your custom events. This allows you to manage your event handling logic in one place, for all your non-element-specific events.

    $(document).ready(function() {
    
      $(body).append('<div id="receiver">');
    
      $("#receiver").bind("foo_event", function () {
        // decide what to do now that foo_event has been triggered.
      });
    
      $("#some_element").click(function() {
        $("#receiver").trigger("foo_event");
      });
    
    });
    
    0 讨论(0)
提交回复
热议问题