我正在我的应用程序中试验jQuery custom Events
。
在下面的jQuery AJAX请求代码中,我在success
回调中尝试trigger()
我的自定义Event
但它似乎没有触发它。这是否无法在成功回调中完成,需要在其他地方调用?
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
自定义事件订阅者
$(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);
});
答案 0 :(得分:3)
从讨论开始,问题是当事件被触发时,处理程序尚未添加到dom中。
因此,确保在触发事件之前添加事件处理程序将解决问题
答案 1 :(得分:2)
您是否尝试过.trigger()
?
jQuery trigger()
来自他们的文档:
$( "#foo" ).on( "custom", function( event, param1, param2 ) {
alert( param1 + "\n" + param2 );
});
$( "#foo").trigger( "custom", [ "Custom", "Event" ] );
因此,对于您的实施:
$(document).trigger('task-modal-data-loaded',[{
source: 'ajax',
message: 'Task Modal Object Loaded from AJAX Request',
time: new Date()
}]);
听众:
$(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);
});