Reputation: 685
Let say I have function to get templates, if template was never before use it should send request by AJAX and after that return template, if template was used it should be return from cache.
Sample code:
var getTemplate = (function(jQuery){
//full template obj = {url: '', html: ''}
var templates = {test: {url: '/templates/test.html'}};
function getTemplate(templateId){
if(templates[templateId].html){
return templates[templateId];
}
jQuery.ajax({
method: "get",
url: templates[templateId].url
}).success(function(respond){
templates[templateId].html = respond;
});
//no idea what next...
return getTemplate
}
})(jQuery);
Sample use:
var template = getTemplate('test')
should always return /templates/test.html
content
I don't wont use async: false
and any framework. I wont learn how to do that ;)
Upvotes: 2
Views: 153
Reputation: 193261
Since you want to cache templates and resolve them immediately if already avaialbale, you need to make sure API is consistent in both cases. It means that your function should implement some sort of deferred or promise interface. For example:
var getTemplate = (function(jQuery) {
var templates = {
test: {
url: 'templates/test.html'
}
};
return function(templateId) {
if (templates[templateId].html) {
return jQuery.when(templates[templateId].html);
}
return jQuery.ajax({
url: templates[templateId].url
})
.then(function(responce) {
templates[templateId].html = responce;
return responce;
});
}
})(jQuery);
Then usage would be:
getTemplate('test').done(function(html) {
console.log(html);
});
Upvotes: 2
Reputation: 64526
In an async request, it's not possible to return the response because getTemplate
will have already completed immediately after sending the request, and it won't wait for the response.
A simple solution is to allow a callback to be passed:
var getTemplate = (function(jQuery){
//full template obj = {url: '', html: ''}
var templates = {test: {url: '/templates/test.html'}};
function getTemplate(templateId, callback){
if(templates[templateId].html){
callback(templates[templateId]);
}
jQuery.ajax({
method: "get",
url: templates[templateId].url
}).success(function(respond){
templates[templateId].html = respond;
callback(templates[templateId]);
});
}
return getTemplate;
})(jQuery);
Usage:
getTemplate('test', function(template){
console.log(template.html);
});
Side note: you were missing return getTemplate;
which is important.
Upvotes: 2