问题
For complicated elements, is is a good practice to (almost) always have Polymer definition inside a closure to keep all the variables and methods which should only be modified internally private, as opposed to attaching them to the element (e.g. 'this')?
Like following:
<polymer-element name="animating-element">
<script>
(function() {
var privateObj = {};
privateObj.internalState = 0;
//private static method
privateObject.setupState = function(polymerObject) {
if(polymerObject.stateExposedToOutside == /* some conditions */) {
privateObject.internalState = 1;
}
}
Polymer('animating-element', {
stateExposedToOutside: 0,
ready: function() {
privateObj.setupState(this);
this.animate();
},
animate: function() {
}
});
})();
</script>
</polymer-element>
回答1:
This is completely up to you as the element designer. Variables in the closure will be as private
as it gets in JavaScript. Properties on the prototype are generally hackable.
One camp values isolation, and prefers privatizing as much as possible to prevent errors and improve upgrade-ability.
Another camp values open APIs, and prefers allowing the developer access, in order to solve problems the author didn't envision.
You get to decide which camp you are in (or invent a new one =P).
回答2:
No! There is one major problem with above code. Since privateObj is sealed by the closure, it is static (e.g. shared among all the instances of that component) and cannot keep the state for each of them.
Moreover the idea is that the state of each component solely be determined by its attributes so keeping an internal state object should be avoided.
来源:https://stackoverflow.com/questions/24442200/almost-always-have-polymer-definition-inside-a-closure