tags:

views:

21

answers:

2

How do I have a widget listen for clicks on other widgets but not listen to normal clicks on itself. For example:

var $dialogWidget = jQuery('#dialogWidget');

$dialogWidget
  .bind('click.btn1.otherWidget',doSomething)
  .bind('click.btn2.otherWidget',doSomething2)
  .bind('click.btn1.otherWidget2',doSomething3);

The problem with this code is that when I click anywhere on $dialogWidget, all of these events that I have bound will be triggered. What I want is this

var $otherWidget = jQuery('#otherWidget');
var $btn1 = $otherWidget.find('a.btn1');
$btn1
    .click(function(){
        $dialogWidget.trigger('click.btn1.otherWidget');
     });

This should be the only way that 'click.btn1.otherWidget' event is fired for $dialogWidget.

One possible thing I could do that would be a hack is anytime I am manually firing a click event is to use 'clicked' instead of click, but that feels like a hack. Any ideas?

+1  A: 

I think the simplest solution is to rename your events, use a name that's not taken. In this case, just don't use click, do something like this instead:

$dialogWidget
  .bind('myClick.btn1.otherWidget',doSomething)
  .bind('myClick.btn2.otherWidget',doSomething2)
  .bind('myClick.btn1.otherWidget2',doSomething3);

Then when you trigger it:

$dialogWidget.trigger('myClick.btn1.otherWidget');

This was click won't trigger your namespace custom events that you don't want fired any other way. To be clear this isn't a hack, it's completely normal jQuery behavior, it's intentionally supported throughout the jQuery event model. Google for jQuery custom events, there are a lot of resources out there around this.

Nick Craver
Thanks again Nick, I guess I just wanted to see if there were other ways to do this. Much appreciated
Adrian Adkison
+1  A: 

You could use event delegation here and try to handle what to do by event.target property.

var $widgets = jQuery('.widget');
$widgets.click(function(event){
  if($(event.target).attr("id") !== "dialogWidget"){
      alert("You won't see this alert if you click on #dialogWidet");
  }
});

This might help you.

Sinan Y.