向现有事件侦听器添加功能

Add functionality to an existing event listener

我在一个表单上有一组输入,用于交互、验证或两者。在这两种情况下,我不确定如何在不覆盖先前分配的情况下添加第二组功能。

举个例子。我有一个字段应该被监视以进行实时验证,并且应该被监视以进行一些实时格式化。 (是的,我可以将它们合并到同一个函数中,但我更愿意将它们分开)。

这是验证分配:

exampleField

    // for live typing
    .keyup($.debounce(500, debouncedValidation))

    // for copy-pastes and autofills
    .change(function(){
        validateInput(formInValidation, $(this));
    });

此外,我想 运行 一些互动功能,例如:

exampleField

    // for live typing
    .keyup($.debounce(500, interactWithElement($(this))))

    // for copy-pastes and autofills
    .change(function(){
        interactWithElement($(this));
    });

我正在使用相同的事件,所以后者会覆盖前者。我的直觉告诉我,有一种优雅的方法可以在两者之间添加一个实用函数,比如 addEventListenerWithoutOverride(),它会查找现有事件并将它们组合起来。那是疯了吗?所述函数的虚构输出可能类似于:

exampleField

    .keyup(
         $.debounce(
             500,
             function(){
                 debouncedValidation();
                 interactWithElement($(this));
             });
         )
    )

    .change(function(){
        validateInput(formInValidation, $(this));
        interactWithElement($(this));
    });

就用on代替?您可以注册任意数量的侦听器w/o担心覆盖。

$('#bind-example').on('click', function(){alert('First click!'); });
$('#bind-example').on('click', function(){alert('Second click!'); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="bind-example" href="#">Click Me!</a>

如果我误解了你的问题,请告诉我。

引用自 OP 的问题:

I'm using the same events, so the later overrides the former.

其实不然。根据 jQuery's .bind documentation:

When an event reaches an element, all handlers bound to that event type for the element are fired. If there are multiple handlers registered, they will always execute in the order in which they were bound. After all handlers have executed, the event continues along the normal event propagation path.


所以,让我们先把文档放在一边,然后测试它是否真的覆盖了之前的事件:

var overriden = true;
$("button").click(function() {
    overriden = false;
});
$("button").click(function() {
    alert("Overriden? " + overriden);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button>Test overriden events.</button>