How to create a singleton element in Polymer

I want to create an element that the user can create only once.

So far, the best I can think of is to define an element inside an anonymous function and throw an error when I find that the element already exists. Is there a way for him to simply reject creation?

(function(){
  var singleton = false;
  Polymer({
   is:'my-singleton',
   created:function(){
    if(singleton) {
     throw new Error ('only one my-singleton should be created');
    }
    singleton = this;
   }
  });
})();
+4
source share
2 answers

There seems to be an undocumented function for the elements remove(). I just moved the code earlier into a function attachedand saved a variable that marks if I am activated 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;
  }
 });
})();

It works very well.

+3
source

Do you want to limit the number of <my-singleton>pages per page or just have a single point state?

/ , :

(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++;
        }
    });
})();
+2

Source: https://habr.com/ru/post/1615252/


All Articles