I'm working on an Json/AJAX implementation in my Symfony2 project. Everything works (modals, redirects, etc.) but my "fire event" implementation isn't.
This is my code:
$(document).trigger(data.content, [data.data]);
The data.content
contains the name of the event, in this case "lesson_editor.added_step" and the data.data
contains a HTML string.
I get the error Uncaught TypeError: undefined is not a function
in the jQuery library. With the Chrome debugger the above trigger is the line which causes it.
If I replace the data.content
with the string "my.test"
it works.
Thanks for you help.
Full JSON string:
{"type":"event","content":"lesson_editor_added_step","data":"\n <div class=\"panel\">\n <div class=\"panel-heading\">\n <span class=\"panel-title\">\n <a data-toggle=\"collapse\" data-parent=\"#steps\" href=\"#step25\">\n asdfasdfasdf\n <\/a>\n <\/span>\n <div class=\"pull-right\">\n <a href=\"#\" class=\"btn btn-xs btn-success\" data-toggle=\"tooltip\" title=\"Add action\">\n <i class=\"fa fa-plus\"><\/i>\n <\/a>\n <a href=\"#\" class=\"btn btn-xs btn-warning\" data-toggle=\"tooltip\" title=\"Edit step\">\n <i class=\"fa fa-edit\"><\/i>\n <\/a>\n <a href=\"#\" class=\"btn btn-xs btn-danger\" data-toggle=\"tooltip\" title=\"Delete step\">\n <i class=\"fa fa-times\"><\/i>\n <\/a>\n <\/div>\n <\/div>\n <div id=\"step25\" class=\"panel-collapse collapse in\">\n <div class=\"panel-body\" id=\"actions25\">\n <\/div>\n <\/div>\n <\/div>\n","flashBag":{"success":["Step added"]}}
AJAX Call
the URL
$.ajax({
url: url,
type: type,
data: data,
beforeSend: this.options.beforeSendCallback
})
.done($.proxy(function(data) {
if (data.type === undefined) {
alert("Ajax data invalid");
return false;
}
// Switch data type
switch (data.type) {
case 'modal':
// Create modal
$(document).bootstrapModal("createModal", data.content);
break;
case 'redirect':
// Redirect to page
window.location.replace(data.content);
break;
case 'event':
// Fire a custom event
$(document).trigger(data.content, [data.data]);
break;
}
// Check if flashbag exists
if (data.flashBag) {
$.each(data.flashBag, function(type, messages) {
$.each(messages, function(index, message) {
new PNotify({
type: type,
text: message
});
});
});
}
// Fire event
$(document).trigger('ajax_done', [data.data]);
}), this)
.fail(this.options.failCallback);
Its best to fire the custom event if its dynamic with:
$(document).trigger(data.content, data.data);
and catch it with an .on event handler:
$(document).on(data.content, function(event, args...) {
// do something beneficial for your career here
});
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.