I have a module, that fetches some object. Then other modules can use this object. Here is a little example of this task:

var Structure = (function(){

    var tree = null,

        df = $.ajax({
            'url'       : '/some/path',
            'type'      : 'POST',
            'data'      : { some : 'data' },
            'dataType'  : 'json'

        ready = function(cb){
            if (tree) {

                tree = TreeHandler.create(data);

    return {
        df      : df,
        ready   : ready


// Usage:
     console.log (data);
     // some actions with data

Am I right on doing this? How can this be made better?

  • \$\begingroup\$ Basically this is completely fine, however I would say it's unnecessarily complex. Can you expand on why you think you need this and can't just use a AJAX call with a callback function? \$\endgroup\$ – RoToRa Dec 28 '11 at 18:03
  • \$\begingroup\$ For example there are a lot of modules for this application, and all of them are able to use the structure obj. If module1 has already fetched the obj, module8 doesn't have to fetch it again. I imagine a way with synchronous AJAX call. After it all modules can simple use fetched object via variable name, but synchronous calls are evil - they block the browser. \$\endgroup\$ – Larry Cinnabar Dec 29 '11 at 1:23
  • \$\begingroup\$ See api.jquery.com/jQuery.Callbacks for some ideas, like: $.Callbacks('once memory') \$\endgroup\$ – biziclop Dec 30 '11 at 20:12

I'm repeating @RoToRa for the sake putting it in answer form for beta-stats:

Your syntax is fine. Without knowing more of the problem domain, it does seem a little unnecessary. Why not use callbacks on your $.ajax() call?


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.