\$\begingroup\$
\$\endgroup\$
3
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) {
cb(tree);
return
}
$.when(df).then(function(data){
tree = TreeHandler.create(data);
cb(tree);
});
};
return {
df : df,
ready : ready
};
})();
// Usage:
Structure.ready(function(data){
console.log (data);
// some actions with data
});
Am I right on doing this? How can this be made better?
asked Dec 28, 2011 at 0:06
1 Answer 1
\$\begingroup\$
\$\endgroup\$
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?
answered Dec 28, 2011 at 22:25
default
structure
obj. Ifmodule1
has already fetched theobj
,module8
doesn't have to fetch it again. I imagine a way withsynchronous
AJAX call. After it all modules can simple use fetched object via variable name, but synchronous calls are evil - they block the browser. \$\endgroup\$