Search code examples
javascriptsingletonquill

Unable to instantiate an obj into a file and use it in another


I'm trying to implement the singleton pattern in order to instantiate an object in a file and reuse the same instance in another file. It's obvious that I'm not understanding something elementary. Any directions for a better understanding?

let editorDiv = document.createElement('div');
editorDiv.setAttribute('id','editor');
document.body.appendChild(editorDiv);

//a.js
function singleton(){
  let _singleton;
  let quillOptions = { modules: { toolbar: true },
                  placeholder: 'Compose an epic...',
                  theme: 'snow'
                }  
  if (!_singleton) {
    _singleton = new Quill('#editor', quillOptions) 
  }
  
  return _singleton;
}

//b.js
//instantiate
let quill = singleton();

//c.js
//get instance in order to use api
let quillInstace = singleton(); 
//Ex: quillInstance.getText(); 
<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>


Solution

  • The problem here is that your _singleton cache variable is scoped inside your singleton() method, meaning that each time you call it, it would be empty.

    You should store it differently:

    //a.js
    //this is now a global var for this file
    let _singleton;
    
    function singleton(){
      let quillOptions = { modules: { toolbar: true },
                      placeholder: 'Compose an epic...',
                      theme: 'snow'
                    }  
      if (!_singleton) {
        _singleton = new Quill('#editor', quillOptions) 
      }
    
      return _singleton;
    }
    

    or use the handful lodash memoize method that does the job for you =)