var Api, $root; Api = { getSandboxedJQuery: function get$($target){ return function(){ var selector = null, args = Array.prototype.slice.call(arguments); if (args.length == 1 && (typeof (selector = args[0]) == 'string')){ return $.apply(this, args.concat($target)); } return $.apply(this, arguments); }; } }; $root = $('.root'); $(function(Api){ var $ = Api.getSandboxedJQuery($root); alert('Initial state: both divs are green. Color will be applied to the selected elements.'); jQuery('.target').css('background-color', 'yellow'); alert('Yellow background applied to selected elements. Even elements outside our root element have been selected.'); $('.target').css('background', 'pink'); alert('Pink background applied to selected elements. No elements outside our root element have been selected.'); }(Api));
<!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <title>Sandbox jQuery in a module</title> </head> <body> <div class="root"> <div class="target hit"></div> </div> <div class="target miss"></div> </body> </html>
body { text-align: center; } .target { height: 100px; width: 100px; background-color: green; border: solid 1px black; margin-top: 20px; }