This repository has been archived by the owner on Mar 13, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
polymer-shared-lib.html
91 lines (87 loc) · 2.69 KB
/
polymer-shared-lib.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<!--
Copyright 2013 The Polymer Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
<link rel="import" href="../polymer/polymer.html">
<polymer-element name="polymer-shared-lib" attributes="url notifyEvent">
<script>
(function() {
Polymer('polymer-shared-lib', {
notifyEvent: 'polymer-shared-lib-loaded',
ready: function() {
},
urlChanged: function() {
requireApi(this);
},
provide: function() {
this.async('notify');
},
notify: function() {
this.fire(this.notifyEvent, arguments);
}
});
function nameFromInstance(instance) {
return instance.url.replace(/[\:\/\%\?\.\=]/g, '_') + '_api';
}
var apiMap = {};
function requireApi(instance) {
instance._api_name = nameFromInstance(instance);
var loader = apiMap[instance._api_name];
if (!loader) {
loader = new Loader(instance);
apiMap[name] = loader;
}
loader.requireApi(instance);
}
Loader = function(instance) {
this.instances = [];
this.load(instance);
};
Loader.prototype = {
loaded: false,
requireApi: function(instance) {
if (this.loaded) {
this.provide(instance);
} else {
this.instances.push(instance);
}
},
load: function(instance) {
this.callbackName = instance._api_name + '_loaded';
window[this.callbackName] = this.success.bind(this);
var url = instance.url.replace('%%callback%%', this.callbackName);
this.addScript(url);
},
addScript: function(src) {
var script = document.createElement('script');
script.src = src;
script.onerror = this.error.bind(this);
var s = document.querySelector('script');
s.parentNode.insertBefore(script, s);
this.script = script;
},
removeScript: function() {
if (this.script.parentNode) {
this.script.parentNode.removeChild(this.script);
}
this.script = null;
},
error: function() {
this.cleanup();
},
success: function() {
this.cleanup();
this.result = Array.prototype.slice.call(arguments);
this.instances.forEach(this.provide, this);
},
cleanup: function() {
delete window[this.callbackName];
},
provide: function(instance) {
instance.notify.apply(instance, this.result);
}
};
})();
</script>
</polymer-element>