Triggering custom events in AJAX callbacks
- by Sabrina Gelbart
I'm pretty new to JavaScript, but one of the things that's been frustrating is that our AJAX callbacks have been getting packed with different functionality, making it difficult to keep everything separated and organized.
I'm really new to programming, I have a feeling learning MVC a bit more would help me, but for now using custom events seems like it could help me keep my code a lot cleaner and prevent some problems. Here's what I'm talking about:
function myAjaxFunction(){
$.post('ajax/test.html', function(data) {
$(document).trigger('testDataLoaded',data);
});
}
function myOtherFunctionThatsDependentUponAjax(){
$(document).one('testDataLoaded', function(data){
alert (data);
}
}
I also don't know if it's ok that I'm triggering document or not...
Are there any patterns that look like this that I can read more about? What are the potential problems with this?