Reputation: 7687
I've got a number of custom elements defined in an app that I'm working on. Right now, I've been prototyping my elements and have the names sitting in the global namespace. Each element has its own HTML file which I import when I need to create the element. A basic HTML file would look like this:
<script type="text/javascript" src="hello-world.js"></script>
This points to the following js file:
var helloWorldPrototype = {
is : "hello-world",
};
Polymer(helloWorldPrototype);
I've got other custom elements which I would then like to have use the prototype of this web component as a base, which I'm accomplishing using the 'behaviors' attribute that Polymer provides. All of the dependencies are imported in the HTML, so my second HTML looks like this:
<link rel="import" href="hello-world.html">
<script type="text/javascript" src="hello-earth.js"></script>
This has the corresponding js contained in hello-earth.js
:
var helloEarthPrototype = {
is : "hello-earth",
behaviors : [helloWorldPrototype]
};
Polymer(helloEarthPrototype);
My problem is that I would now like to get all of those prototype objects out of the global namespace. For the hello-world
component, I can do this by encapsulating my prototype in a self-executing function block, like so:
(function(){
var helloWorldPrototype = {
is : "hello-world",
};
Polymer(helloWorldPrototype);
})();
The problem with this is that helloWorldPrototype
is no longer available to helloEarthPrototype
. How can I avoid placing the prototypes for my custom elements in the global namespace, but still give them access to one another for inheritance purposes?
Upvotes: 0
Views: 98
Reputation: 31181
If you want to share objects across different JavaScript files, you'll need at least one global object
reference. Inside it you can add (as attributes
) the resources you want to share.
For exemple, you can define an object named MyAppNS
, that will act as a namespace:
var MyAppNS = {} // or window.MyAppNS = {}
Then you can define you first prototype and Custom Element:
MyAppNS.helloWorldPrototype = {
is: "hello-world"
}
Polymer( MyAppNS.helloWorldPrototype )
In another file you can define another prototype and Custom Element:
MyAppNS.helloEarthPrototype = {
is : "hello-earth",
behaviors : [MyAppNS.helloWorldPrototype]
}
Polymer( MyAppNS.helloEarthPrototype )
Upvotes: 1