9

jQuery provides a isTrigger property which allows us to know if the event was a "real event" or was it only "triggered".

$(ele).on("click", function(e){
    if(e.isTrigger){
       // this event was only triggered, not a real event 
    }else{
      // this was a real event 
    }
}) 

For unit-testing purposes, is there a way to trigger a event and somehow overwrite the isTrigger property.. and in the event callback still behave (by having isTrigger === false) as if it was a real click event.. Was trying the following code:

var triggerClick = jQuery.Event("click", {
    isTrigger:false,
    data:{
        isTrigger:false
    }

but it doesn't seem to pass it correctly..

4

3 回答 3

5

原生方式怎么样,完全避免使用 jQuery isTrigger:

function simulateClick(elem) {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, elem,
          0, 0, 0, 0, 0, false, false, false, false, 0, null);
  if (document.createEvent) {
     elem.dispatchEvent(evt);
  } else {
     elem.fireEvent("on" + evt.eventType, evt); // support for IE crap
  }
}

要使用它,您只需执行以下操作:

$(ele).on("click", function(e){
    if(e.isTrigger){
       // this event was only triggered, not a real event 
       console.log('triggered');
    }else{
       // this was a real event 
       console.log('clicked');
    }
});

simulateClick(ele);

小提琴

于 2013-05-14T15:52:20.250 回答
1

如果您担心事件是由用户触发还是由代码触发,也许您应该提取一个方法并直接调用该方法。然后,您可以添加一个userTriggered参数并传递 true 或 false。

$(ele).on("click", function(e){
    doWork($(this), e, true);
}

doWork($(ele), null, false);

function doWork(item, e, userTriggered)
{
    if(userTriggered) {
    }
    else {
    }
}

然后,当您测试您的 doWork 方法时,您可以传入userTriggeredtrue 或 false 以测试所需的行为。这也从您的测试中消除了浏览器行为的依赖性,这是一件好事。

于 2013-05-14T16:01:46.433 回答
1

@adeneo 的回答给了我错误。(未捕获的 TypeError:无法在“MouseEvent”上执行“initMouseEvent”:参数 4 不是“Window”类型。)

这个方法对我有用(虽然 isTriggered 是未定义的,不是假的)

$('#myBtn').on('click', function(e){
  alert('isTrigger: ' + e.isTrigger)
});

 var event = new Event('click');
$( "#myBtn" )[0].dispatchEvent(event);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" id="myBtn">dude</a>

于 2017-06-19T23:27:21.307 回答