简体   繁体   English

jQuery 自定义事件未在 AJAX 成功回调中触发

[英]jQuery Custom Event not triggering in AJAX Success Callback

I am experimenting with jQuery custom Events in my Application.我正在我的应用程序中试验 jQuery custom Events

In the jQuery AJAX request code below, in the success callback I am trying to trigger() my custom Event在下面的 jQuery AJAX 请求代码中,在success回调中我试图trigger()我的自定义Event

It does not seem to be triggering it though.它似乎并没有触发它。 Will this simply not be able to be done in the success callback and needs to be called elsewhere?这是否根本无法在成功回调中完成并需要在其他地方调用?

jQuery AJAX request code jQuery AJAX 请求代码

// Request Task Record using AJAX Request to Server
var jqXHR = $.ajax({
    type: 'POST',
    async: false,
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    url: projectTaskModal.cache.getTaskRecordUrlEndpoint,
    data: {
        action: 'load-task-record',
        task_id: taskId
    },
    success: function(data) {

        // NON RELEVANT CODE REMOVED FOR DEMO

        // Event that is not being triggered....
        // Publish 'task-modal-data-loaded' Event to Subscribers
        $.event.trigger({
            type: 'task-modal-data-loaded',
            source: 'ajax',
            message: 'Task Modal Object Loaded from AJAX Request',
            time: new Date()
        });

    }
}); // end AJAX request

Custom Event Subscriber自定义事件订阅者

$(document).on('task-modal-data-loaded', function(event) {
    //alert('Task Modal Object Loaded');
    console.log('CUSTOM APP EVENTS: Event: task-modal-data-loaded Source: '+event.source+' Message: '+event.message+' Time: '+event.time);
});

From the discussion, The problem is when the event is triggered the handler is not yet added to the dom.从讨论中,问题是当事件被触发时,处理程序尚未添加到 dom。

So making sure that the event handler is added before the event is fired will solve the probelm因此,确保在触发事件之前添加事件处理程序将解决问题

Have you tried just .trigger() ?您是否尝试过.trigger() jQuery trigger() jQuery 触发器()

from their docs:从他们的文档中:

$( "#foo" ).on( "custom", function( event, param1, param2 ) {
  alert( param1 + "\n" + param2 );
});
$( "#foo").trigger( "custom", [ "Custom", "Event" ] );

So for your implementation:因此,对于您的实施:

$(document).trigger('task-modal-data-loaded',[{
        source: 'ajax',
        message: 'Task Modal Object Loaded from AJAX Request',
        time: new Date()
    }]);

And the listener:和听众:

$(document).on('task-modal-data-loaded', function(event,data) {
//alert('Task Modal Object Loaded');
    console.log('CUSTOM APP EVENTS: Event: task-modal-data-loaded Source:    '+
      data.source + ' Message: ' + data.message + ' Time: ' + data.time);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM