Triggering custom events in AJAX callbacks

Posted by Sabrina Gelbart on Programmers See other posts from Programmers or by Sabrina Gelbart
Published on 2012-02-28T12:48:25Z Indexed on 2012/04/14 23:45 UTC
Read the original article Hit count: 542

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?

© Programmers or respective owner

Related posts about JavaScript

Related posts about AJAX