Sandbox jQuery

First try to sandbox $ (jQuery) to a specific element:

HTML:

<div id = "test">
  <h2>TEST</h2>
</div>
<h2>TEST 2</h2>

Javascript:

function Module() {
}

function Sub () {
	console.log($('h2'));

};

Sub.prototype = new Module();

Sub();

console.log($('h2'));

function $() {
	var args = Array.prototype.slice.call(arguments);
	var callerFunction = arguments.callee.caller;
	if (callerFunction && callerFunction.prototype.constructor == Module) {
		return window.jQuery(args[0], '#test');
	}
	return window.jQuery.apply(null,args);
}

Result: Doesn’t work with chaining.

Second try

if (typeof Object.create !== 'function') {
      Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
      };
    }

var Module = function () {
	var pub = {};
	pub.test = "true";
	return pub;
	}()

var Sub = function () {
	var pub = {};
	pub.test2=function () {
		$('h2').html("test");
		};
	return pub;
	}()

var instance = function () {
	this.$ = function (selector) {
		return window.jQuery(selector, '#test');
		};
	var pub = window.jQuery.extend(Object.create(Sub), Module);
	return pub;
}()

$(document).ready(function () {
	instance.test2();
});

Success!

About Tor Brekke Skjøtskift

Senior Webdesigner Media Norge Digital
This entry was posted in Javascript, jQuery. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>