2

I am trying to construct a wrapper for an element and I want to create a seamless integration for my wrapper. To achieve this, I want to propagate all events from one element to another, to create a mirror to say so.

Let's say I have #element-1 and #element-2. I give #element-1 a 'click' handler. The desired behaviour is that whenever a click occurs, either on #element-1 or #element-2, the handler should fire. Also, if #element-2 is assigned a different 'click' handler, both handlers should trigger.

Do not worry about infinite bubbling, I will find a mechanism to counter that. My question is how can I achieve this event mirroring for all possible events for these two elements, without writing all the event names (I'd also like to get custom events, so hard-coding the event names is not an option)?

I'm open to solutions that may not use jQuery, as long as it achieves what I described.

Ian
  • 50,146
  • 13
  • 101
  • 111
Cosmin Stamate
  • 145
  • 1
  • 1
  • 11
  • http://stackoverflow.com/q/9735608/139010 – Matt Ball Jun 06 '13 at 02:32
  • From what I see, .data('events') retrieves the _bound_ events list, which is not live. Any way I can make this apply for any event that might be bound in the future, without having a timer or something similar? – Cosmin Stamate Jun 06 '13 at 02:42
  • Not AFAIK. There is no wildcarding or similar with events. You _might_ be able to do it by overriding `$.fn.bind`. – Matt Ball Jun 06 '13 at 02:50
  • A timer is preferable to overriding jQuery properties, because I am writing a plugin which I aim to make as unobtrusive as possible. I feared I might not have another option. Thank you! (I am a newbie here, is there any way I can give reputation for comments?) – Cosmin Stamate Jun 06 '13 at 02:54
  • (No, to the rep for comments question) – Matt Ball Jun 06 '13 at 03:45

1 Answers1

0

Suppose there are 10 anchor elements inside div ids #event-1, #event-2, ... #event-10. You can write the event handlers as below.

for(i=0;i<=10;i++) {
  if ($(".event-"+i).find('a').length > 0) {
    var g = $(".event-"+i).find('a');
    g.click(function(){
      /* Your code */
    });
  }
}