Shared singleton pattern


/ Published in: Other
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /*
  2. A similar pattern to the module pattern is the “shared singleton”-- create a singleton object for an application that can be used to share properties or methods between pages or inline frames.
  3.  
  4. Here’s the start of a “my.js” script that every page or frame in an application could share:
  5. */
  6.  
  7. if (typeof parent.my != “undefined”) {
  8. var my = parent.my; // shared singleton
  9. } else {
  10.  
  11. var my = {};
  12.  
  13. my.something …
  14.  
  15. }
  16.  
  17. /*
  18. The “parent” bit is so that the script can be used with iframes and still
  19. retain a reference to the same “my” instance. If a page is at the top, then parent points to itself.
  20.  
  21. Every page or frame that imports “my.js” can share properties or methods with any other page.
  22.  
  23. */

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.