Sandboxing JavaScript
Today I fired off a tweet that in some developers eyes may have been controversial
But to the point, the task at hand I was trying to solve was to bundle a set of core modules built by Ender along side my own library (that uses Ender), and not populate the global space.
Moreover, I'm not talking about sandbox natives, but something more along the lines of what Dean Edwards wrote in 2006 using iframes — except I don't want to use iframes. They're clunky, slow, and most definitely an unprofessional way of shipping a library
The collisional problem
The moment I require Ender in my library, it conflicts with your (the developer) version of Ender — and/or more importantly (and perhaps the most common use-case) your version of jQuery. The two different $ functions will collide.
The poor man's way of doing this, of course, would ask the developer to kindly call jQuery.noConflict(). (That's pretty un-pro). Likewise if my library calls ender.noConflict() it removes the developers instance of Ender (if one exists).
Enter, context pattern
One specific pattern you'll see in nearly every module (or micro-library for wording-sake) in Ender is the notion of exporting your public interfaces to an outer-scope. See Klass, Valentine, domReady, Query for references.
That pattern looks like this
(function (context) {
context.public = fn
}(this))
Of course, this is seemingly no different than explicitly setting window.public = fn since in this scenario this === window. So what gives? Well...
Enter, sandboxing
Providing the fact that your library is using the context pattern (and not setting public interfaces on window), sandboxing becomes easy
(function () {
with (this) {
{{ender}}
{{library}}
}
}).call({})
In this case {{ender}} represents a custom build of Ender, and {{library}} represents your library's use of that build — all while not exposing the public Ender $ interface. Therefore your library has effectively sandboxed its modules! Pretty cool, eh?
On a final note, don't believe the hype on what is indeed a useful language feature.
recent
- Matador: The Obvious MVC Framework for Node
- Sandboxing JavaScript
- Crouching Ender, hidden command
- Ender.js - The open submodule library
- Qwery - The Tiny Selector Engine
- Klass
- Smallest DOMReady code, ever.
- $script.js - Another JavaScript loader
- About that slowness on Twitter...
- Autocomplete Fuzzy Matching
- JavaScript Cache Provider
- JavaScript Animate
- Asynchronous method queue chaining in JavaScript
- Something changed
- Unofficial Twitter Widget Documentation
i am dustin diaz

