事件监听器完成后调用函数 - Javascript

时间:2015-08-06 19:22:28

标签: javascript jquery

在Javascript中,当EventListener完成运行任何附加代码时,有没有办法调用函数?我正在使用一个使用EventListener的外部库,当调用Listener时,它会执行某个操作。我需要在外部库代码完成运行后运行我的函数。

我想我基本上要求的是EventListener我可以放在EventListener上,以查看EventListenerHandler何时完成任务。< / p>

我无法获取源代码并将其放在我自己的文件中,而且我也无法直接在外部库的Event代码的末尾放置我的函数调用。我也没有发起EventListenerEventListener,所以我不认为我可以在其上放置回调函数(我还是Javascript的新手,所以也许,我&# 39;我不完全确定)。该事件不使用AJAX。

EventListener - &gt; Event - &gt; Event

如何做到这一点?

enter image description here

这是我的EventListeners的图片。在我的特定情况下,我希望在外部库使用has_many_add:after EventListener捕获$('select.user_select').select2({ minimumInputLength: 2 }) 后执行以下代码,并完成在关联的Handler中运行代码:

$(document).on('click', 'a.button.has_many_add', function(e) {
  var before_add, fieldset, html, index, parent, regex;
  e.preventDefault();
  parent = $(this).closest('.has_many_container');
  parent.trigger(before_add = $.Event('has_many_add:before'), [parent]);
  if (!before_add.isDefaultPrevented()) {
    index = parent.data('has_many_index') || parent.children('fieldset').length - 1;
    parent.data({
      has_many_index: ++index
    });
    regex = new RegExp($(this).data('placeholder'), 'g');
    html = $(this).data('html').replace(regex, index);
    fieldset = $(html).insertBefore(this);
    recompute_positions(parent);
    return parent.trigger('has_many_add:after', [fieldset, parent]);
  }
});

单击按钮时,外部库会执行回调:

has_many_add:after

我无法更改此代码,我需要我的功能才能将此次调用转至EventListener $(".button has_many_add").click(function(){ $('select.user_select').select2({ minimumInputLength: 2 }); }); 。我尝试使用:

scala> Array(1.1, 4.4, 9.9).map(math.log(_))
res21: Array[Double] = Array(0.09531017980432493, 1.4816045409242156, 2.2925347571405443)

此代码似乎在外部库的事件处理程序执行之前执行。

2 个答案:

答案 0 :(得分:1)

只要您的外部库不会阻止事件冒泡,您就应该能够这样做:

$(document).on('has_many_add:after', function(){
    //do your stuff
});

答案 1 :(得分:0)

这是一个非常常见的事情,特别是在jQuery中。大多数jQuery函数实际上通过回调来支持它。

以下是一个例子:

$(document).on('click', 'div', function() {
    console.log("a div got clicked, so naturally we're running cool stuff when it completes");
});

在该示例中,console.log以及这些回调括号之间的所有内容仅在文档上单击div时才会运行。

您还可以在此侦听器之外定义一个函数,然后在触发回调时从内部调用它:

function myFunction (){ 
    console.log("doing more stuff after the event listener is triggered"); 
});

$(document).on('click', 'div', function() {
    console.log("a div got clicked, so naturally we're running cool stuff when it completes");
    myFunction(); // invokes our other function
});