JS sandbox pattern implementation


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

http://stackoverflow.com/questions/3628649/javascript-self-contained-sandbox-events-and-client-side-stack


Copy this code and paste it in your HTML
  1. (function(global) {
  2. var Sandbox = function(modules, callback) {
  3. if (!(this instanceof Sandbox)) {
  4. return new Sandbox(modules, callback);
  5. }
  6. // modules is an array in this instance:
  7. for (var i = 0, len = modules.length; i < len; i++) {
  8. installedModules[modules[i]](this);
  9. }
  10. callback(this);
  11. };
  12. Sandbox.modules = {};
  13. global.Sandbox = Sandbox;
  14. })(this);
  15.  
  16. // Example module:
  17. // You extend the current sandbox instance with new functions
  18. Sandbox.modules.ajax = function(sandbox) {
  19. sandbox.ajax = $.ajax;
  20. sandbox.json = $.getJSON;
  21. };
  22.  
  23. // Example of running your code in the sandbox on some page:
  24. Sandbox(['ajax'], function(sandbox) {
  25. sandbox.ajax({
  26. type: 'post',
  27. url: '/Sample/Url',
  28. success: function(response) {
  29. // success code here. remember this ajax maps back to $.ajax
  30. }
  31. });
  32. });

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.