0

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
  • apparrently jQuery supports exclusive events. So $dialogWidget.trigger('click!') would only trigger the 'click' and not 'click.namespace' events. I need the opposite of this. Something like $dialogWidget.bind('click.namespace!') which would mean only items that manually fire this the fully qualified event would trigger this Commented Aug 5, 2010 at 22:35

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks again Nick, I guess I just wanted to see if there were other ways to do this. Much appreciated
2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.