UNPKG

2.45 kBPlain TextView Raw
1import {Bean} from "./context/context";
2import {Qualifier} from "./context/context";
3import {Autowired} from "./context/context";
4
5@Bean('templateService')
6export class TemplateService {
7
8 @Autowired('$scope') private $scope: any;
9
10 private templateCache:any = {};
11 private waitingCallbacks:any = {};
12
13 // returns the template if it is loaded, or null if it is not loaded
14 // but will call the callback when it is loaded
15 getTemplate(url: any, callback: any) {
16
17 let templateFromCache = this.templateCache[url];
18 if (templateFromCache) {
19 return templateFromCache;
20 }
21
22 let callbackList = this.waitingCallbacks[url];
23 let that = this;
24 if (!callbackList) {
25 // first time this was called, so need a new list for callbacks
26 callbackList = [];
27 this.waitingCallbacks[url] = callbackList;
28 // and also need to do the http request
29 let client = new XMLHttpRequest();
30 client.onload = function () {
31 that.handleHttpResult(this, url);
32 };
33 client.open("GET", url);
34 client.send();
35 }
36
37 // add this callback
38 if (callback) {
39 callbackList.push(callback);
40 }
41
42 // caller needs to wait for template to load, so return null
43 return null;
44 }
45
46 handleHttpResult(httpResult: any, url: any) {
47
48 if (httpResult.status !== 200 || httpResult.response === null) {
49 console.warn('Unable to get template error ' + httpResult.status + ' - ' + url);
50 return;
51 }
52
53 // response success, so process it
54 // in IE9 the response is in - responseText
55 this.templateCache[url] = httpResult.response || httpResult.responseText;
56
57 // inform all listeners that this is now in the cache
58 let callbacks = this.waitingCallbacks[url];
59 for (let i = 0; i < callbacks.length; i++) {
60 let callback = callbacks[i];
61 // we could pass the callback the response, however we know the client of this code
62 // is the cell renderer, and it passes the 'cellRefresh' method in as the callback
63 // which doesn't take any parameters.
64 callback();
65 }
66
67 if (this.$scope) {
68 let that = this;
69 setTimeout(function () {
70 that.$scope.$apply();
71 }, 0);
72 }
73 }
74}