是否可以从jquery中侦听自定义原型事件?

时间:2018-06-02 04:41:30

标签: javascript jquery prototypejs

如果我在prototype.js中触发自定义事件,我可以在jquery中监听该事件吗?

我尝试了这个,但它不起作用

$.noConflict();

$('target').observe('custom:event', function(){
  console.log("prototype method");
});

jQuery("#target").on("custom:event",function(){
  console.log("jquery method");
});

$('target').fire('custom:event');
<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="target"></div>

1 个答案:

答案 0 :(得分:1)

您可以,但不要使用自定义事件的名称。您可以为事件dataavailable设置一个事件监听器,因为这是Prototype设置要经历的任何自定义事件。

  

https://github.com/sstephenson/prototype/blob/560bb59414fc9343ce85429b91b1e1b82fdc6812/src/prototype/dom/event.js#L635

if (isCustomEvent(eventName))
  observeCustomEvent(element, eventName, responder);
else
  observeStandardEvent(element, eventName, responder);
     

https://github.com/sstephenson/prototype/blob/560bb59414fc9343ce85429b91b1e1b82fdc6812/src/prototype/dom/event.js#L654

 function observeCustomEvent(element, eventName, responder) {
    if (element.addEventListener) {
      element.addEventListener('dataavailable', responder, false);
    } else {
      // We observe two IE-proprietarty events: one for custom events that
      // bubble and one for custom events that do not bubble.
      element.attachEvent('ondataavailable', responder);
      element.attachEvent('onlosecapture',   responder);
    }
  }

所以要听一个Prototype事件做类似的事情:

jQuery("#target").on("dataavailable",function(e){
  if(e.originalEvent.eventName == "custom:event"){
    doWhatever();
  }
  //Or even do a trigger through jQuery by passing the 
  //event target and event name
  //this will allow you to just set events like you were
  //with jQuery and not need a bunch of if statements
  jQuery(e.target).trigger(e.originalEvent.eventName);
});

演示

jQuery.noConflict();
var protoTarget = $('target');
var jQueryTarget = jQuery('#target');

protoTarget.observe('custom:event', function(e){
  protoTarget.append('Prototype callback');
});

jQuery(document).on("dataavailable",function(e){
  jQuery(e.target).trigger(e.originalEvent.eventName);
});

jQueryTarget.on("custom:event",function(){
  jQueryTarget.append("<br>jQuery callback");
});

$('target').fire('custom:event');
<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="target"></div>