开发者

Trigger an event for all listeners except the trigger itself

I have a couple of links bound to a custom event. The event is triggered by hovering any of those links. However I don't want it to be triggered on the link that I actually hovered.

I can think of a couple of possible solutions

  1. I put an "if" in the callback function for the event and somehow check if the triggering object is the object trying to run the callback function and deal with t accordingly. Can objects be compared in a convenie开发者_StackOverflownt and effective fashion?

  2. Temporarily unbind the listener of the object firing the event and then rebind it afterwards. This doesn't sound bulletproof since the event might be rebound before it was actually triggered? I'm not sure how those types of event queues is handled. Will the jquery.trigger actually affect all listeners before the next statement is executed? The other downside is that it might be considered a hack instead of good practice? You opinion?

  3. Skip the whole event-bind-trigger thing and just collect every object in an array and let the hover callback function iterate through this doing whatever I want. I guess that's actually somethink like what's actually happening behind the curtains in the to above scenarios

Is there a common practice for solving this problem? Something in the observer pattern perhaps?


Give each of the links an ID and a class. When the mouse enters the active area of one of your special links, fire your custom event on all of them with the ID of the link over which the mouse is hovering. Have your custom event handler check to make sure the that ID doesn't match the ID of the links that receive notice of the event.

<a class="fancy-hover" id="1" href="foo">Example Link 1</a>
<a class="fancy-hover" id="2" href="bar">Example Link 2</a>
<a class="fancy-hover" id="3" href="qux">Example Link 3</a>

<script type="text/javascript">
    // custom event
    $("a.fancy-hover").bind('mouseOverOneOfUs',function(event, whatMouseHoversOver){

        // Prevent item mouse is over from responding.
        if (whatMouseHoversOver != this.id) {
            // do something
        }
        return false; // Stop propagation up the DOM tree. Remove to allow propagation.
    });

    // When mouse enters the active area of a link with class "fancy-hover",
    //     tell all links in the class which member of the class has the mouse.
    $("a.fancy-hover").mouseenter(function() {

        // this.id is ID of current element,
        //     and we pass the value as an array to our custom event.
        $("a.fancy-hover").trigger('mouseOverOneOfUs', [this.id]);
    });
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜