Create and Retrieve Nested Objects with MooTools

By  on  

One argument that's been lodged by many is that MooTools doesn't encourage the use of namespaces for classes.  The Dojo Toolkit does employ namespaces and provides two helpful functions for working with them:  dojo.getObject and dojo.setObject.  These methods allow for setting and getting of nested objects via strings.  I've ported this functionality MooTools so you can create and retrieve nested objects quickly!

The MooTools JavaScript

Here goes the magic, slightly modified from Dojo:

(function() {

	// Utility method to get and set objects that may or may not exist
	var objectifier = function(splits, create, context) {
		var result = context || window;
		for(var i = 0, s; result && (s = splits[i]); i++) {
			result = (s in result ? result[s] : (create ? result[s] = {} : undefined));
		}
		return result;
	};

	// Creates an object if it doesn't already exist
	Object.extend("place", function(name, value, context) {
		var splits = name.split("."), s = splits.pop(), result = objectifier(splits, true, context);
		return result && s ? (result[s] = value) : undefined;
	});

	// Retrieves an object if not already present
	Object.extend("retrieve", function(name, create, context) {
		return objectifier(name.split("."), create, context);
	});

	// Checks to see if the object exists
	Object.extend("exists", function(name, context) {
		return Object.retrieve(name, false, context) !== undefined;
	});

})();

Both methods use a root method for parsing the string and finding the object, if it exists.  The place method creates the object, accepting the object name, value, and context (base object), creating the object as desired:

// Creates my.namespace.MyClass
Object.place("my.namespace.MyClass", {
	name: "David"
});
// my.namespace.MyClass.name = "David"

// Creates some.existing.objecto.my.namespace.MyClass
Object.place("my.namespace.MyClass", {
	name: "David"
}, some.existing.objecto); // Has to be an existing object

Likewise, the retrieve method searches for the object, and optionally may create it:

// Get an object
Object.retrieve("my.namespace.MyClassToo");

// Try to find an object, create it if it doesn't exist
Object.retrieve("my.namespace.MyClassThree", true);

As a bonus, I've also thrown in an exists method to check for the existence of an object:

Object.exists("my.namespace.MyClassToo"); // returns TRUE or FALSE

Woohoo!  These are some really nice utility methods to have around if you're looking to work with dynamic objects and namespaces!

Recent Features

  • By
    Creating Scrolling Parallax Effects with CSS

    Introduction For quite a long time now websites with the so called "parallax" effect have been really popular. In case you have not heard of this effect, it basically includes different layers of images that are moving in different directions or with different speed. This leads to a...

  • By
    Interview with a Pornhub Web Developer

    Regardless of your stance on pornography, it would be impossible to deny the massive impact the adult website industry has had on pushing the web forward. From pushing the browser's video limits to pushing ads through WebSocket so ad blockers don't detect them, you have...

Incredible Demos

  • By
    MooTools onLoad SmoothScrolling

    SmoothScroll is a fantastic MooTools plugin but smooth scrolling only occurs when the anchor is on the same page. Making SmoothScroll work across pages is as easy as a few extra line of MooTools and a querystring variable. The MooTools / PHP Of course, this is a...

  • By
    MooTools TwitterGitter Plugin

    Everyone loves Twitter. Everyone loves MooTools. That's why everyone should love TwitterGitter, a MooTools plugin that retrieves a user's recent tweets and allows the user to format them however the user would like. TwitterGitter allows the user to choose the number of...

Discussion

  1. I just thought of a new idea for using the current object as context, if present. Stay tuned for an update to the script above!

    • Update made, but the context experiment didn’t work. Shortened the method though.

  2. Thanks David,
    I knew that feature from dojo and really was missing it in Mootools!
    Cheers

  3. My test file is available here: http://davidwalsh.name/dw-content/mootools-object.html . It provides numerous different examples of what’s presented above.

  4. Jani Peltoniemi

    This is a bit cleaner than my version. Thanks.

    Might I suggest changing the order of arguments? In MooTools the context object is always the first argument and yours is the opposite.

    • Jani Peltoniemi

      I also noticed that place() fails if in the context object somewhere along the path is a non-object value. I changed mine to overwrite any existing values, but I’m curious whether or not such behavior is desirable.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!