Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a singleton element in Polymer

Tags:

polymer

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;
   }
  });
})();
like image 788
akc42 Avatar asked Nov 10 '15 13:11

akc42


2 Answers

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++;
        }
    });
})();
like image 78
Chris van Leeuwen Avatar answered Oct 20 '22 23:10

Chris van Leeuwen


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.

like image 3
akc42 Avatar answered Oct 20 '22 23:10

akc42