I am experimenting with jQuery custom Events
in my Application.
In the jQuery AJAX request code below, in the success
callback I am trying to trigger()
my custom 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
// 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.
So making sure that the event handler is added before the event is fired will solve the probelm
Have you tried just .trigger()
? jQuery trigger()
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);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.