jQuery “.triggerHandler()” vs. “.trigger()” when multiple elements are selected

后端 未结 1 639
走了就别回头了
走了就别回头了 2021-02-06 08:26

The jQuery \".triggerHandler()\" mechanism, unlike \".trigger()\", only operates on the first element referenced by the jQuery object for which it\'s called. In other words,

1条回答
  •  囚心锁ツ
    2021-02-06 08:59

    "...is there some rationale for why the two are different in this respect?"

    I think the idea is that triggerHandler() is meant to be a way of invoking the function you as a handler as though it was any other function.

    As such, they made triggerHandler() so that the function is only invoked once, it returns the actual return value of the function, and it doesn't affect the DOM with bubbling or default behaviors.

    Of course the function may break if they changed the this value to something other than a DOM element, so they just use the first element matched.

    If you're wanting to simply use your function, then I'd probably just keep a reference to it and invoke it directly, or as the argument to .each().

    $('.element').each( handler_func );
    

    ...as long as you don't need the event object.


    EDIT: Or if you want the values returned from the invocation, use .map() instead:

    var return_values = $('.element').map( handler_func );
    

    EDIT: With respect to the example provided in the updated question, a good solution may be to take advantage of the extraParameters capability of the trigger()[docs] method so that you can tell the handler to preventDefault() and stopPropagation().

    $('.elememts').bind( 'click', function( e, was_code_triggered ) {
    
        if( was_code_triggered ) {
            e.preventDefault();
            e.stopPropagation();
        }
        // your code
    });
    
    
    // ...
    
    
    $('.elememts').trigger( 'click', true ); // pass "true" to let handler know
                                             //    it wasn't a DOM event
    

    From the .trigger() docs:

    "Note the difference between the extra parameters we're passing here and the eventData parameter to the .bind() method. Both are mechanisms for passing information to an event handler, but the extraParameters argument to .trigger() allows information to be determined at the time the event is triggered, while the eventData argument to .bind() requires the information to be already computed at the time the handler is bound."

    0 讨论(0)
提交回复
热议问题