lundi 29 août 2011
MooTools has always gotten a bit of grief for not inherently using and standardizing namespaced-based JavaScript classes like the Dojo Toolkit does. Many developers create their classes as globals which is generally frowned up. I mostly disagree with that stance, but each to their own. In any event, namespaces are technically just nested objects and I recently shared with you how to create and retrieve nested objects with MooTools. With those utility functions available, I've modified Class so that you can create namespaced classes easily!
The MooTools JavaScript
The technique below is very much like monkey patching:
copy(function() { // Keep reference to the original Class var klass = Class; // Redefine class ("that's deep") Class = function(name, params, context) { // Find out if this is namespaced or the original method var namespaced = (arguments.length > 1); // Add the class name to the param list if(namespaced) params.$name = name; // Create and get the original class var original = new klass(namespaced ? params : name); // If namespaced, set class into namespace if(namespaced) Object.place(name, original, context); // Return this newly created class! return original; }; })();
I keep a reference to the original
Class
, as I'll be using it within my newClass
function. The new signature allows for a namespaced class name, the usual class properties, and the context which may be passed to the Object.place method. The first step is analyzing the arguments provided to Class; if one argument, it's a traditional class; if more than one argument is provided, we know we're trying to create a namespaced class and will act accordingly. You'll also notice that I add a $name
property to the class prototype, providing the given class name to the class for later use. I've found the class' declaredClass property incredibly helpful within Dojo.
Here's how you'd use the new Class function:
copy// Create a namespaced class var myClass = new Class("davidwalsh.ui.Slider", { initialize: function() { // Do stuff! }, doSomething: function(){} }); // myClass === davidwalsh.ui.Slider! // Create an instance of the class var myInstance = new davidwalsh.ui.Slider({ // props }); // Get the name of the declared class var instanceClassName = myInstance.$name; // equals "davidwalsh.ui.Slider"
The first argument becomes the namespace and class name as a string. The second argument is the traditional parameters argument. If only one argument is provided to the Class function, the class is created and returned per usual; in fact, both the namespaced method and traditional method return the newly created class. The method provided above is completely backward compatible so you wont have rewrite your existing code.
Inscription à :
Publier les commentaires (Atom)
Currently have 0 comments: