I want to create an element that a user can only instantiate once.
So far the best I can think of doing is defining the element within an anonymous function and throwing an error when I find the element already exists. Is there a way so it just rejects being created?
(function(){
var singleton = false;
Polymer({
is:'my-singleton',
created:function(){
if(singleton) {
throw new Error ('only one my-singleton should be created');
}
singleton = this;
}
});
})();
Do you want to restrict the number of <my-singleton>
on the page, or just have a singleton 'state'?
To share a singleton state/service between multiple element instances you can do this:
(function() {
'use strict';
// singleton shared connection between all instances of rg-signalr
var singletonState = {
counter: 0
};
Polymer({
is: 'my-element-using-singleton-state',
attached() {
singletonState.counter++;
}
});
})();
I seems that there is an undocumented remove()
function for elements. I just moved the code previously to the attached
function, and keep a variable which notes if I have been made active or not.
(function(){
var singleton = false;
Polymer({
is:'my-singleton',
attached:function(){
if(singleton) {
this.isActive = false;
this.remove();
} else {
singleton = true;
this.isActive = true;
// remainder of element initialization
}
},
detached:function() {
if(this.isActive) singleton = false;
}
});
})();
This seems to work very well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With