Friday, April 20, 2012

How to return promise that will resolve with the result of several functions?

I'm developing a jQuery plugin, which pretends to translate elements on the page, automatically depending on the user's browser language. Translations will be stored in .json files.



When you call the plugin, you pass a package name (or an Array of them) and then it will try to load the language file in the following way:




  • If the browser's language is simple, for example 'en' and you only have indicated a package, it will try to load the following: packageName-en.json

  • If the browser's language is composed, for example 'en-US' it will try to load the same as before but with: packageName-en.json AND packageName-en-US.json

  • If more than one package is indicated, it will try to follow one of the two previous path for each package.



So, in the plugin I have this:



$.fn.Translator = function(pkg, options){
Translator.initialize(pkg, options).done(function(){
return this.each(Translator.translate);
});
};


So, somewhere in my initialize function, I have this:



loadLanguages : function(){
$.each(self.options.packages,function(i, pkg){

});
}


Which will call this function :



getLanguage : function(pkg, language){
var self = this, url;
if (self.options.path)
url = self.options.path + '/';
url += [pkg, language].join('-');

return $.ajax ({
url : url,
dataType : "json",
cache : self.options.cache
});
}


The problem is that since that function will be called probably multiple times, I don't know how to make initialize to return a promise which will be resolved once ALL of the functions have been called.





No comments:

Post a Comment