Variable Properties
by Peter Higgins

The shortest cookie ever: How to assign properties from variable hashes, or: Why dotted notation rocks.

In JS, we have objects:

var foo = {
	name:"person",
	age:42,
	height:"tall"
};

We can access the values contained with foo via dotted notation:

console.log(foo.name, foo.age, foo.height == "tall");
>>> person, 42, true

We can access the dotted values with brackets:

var name = foo["name"];
console.log(name);
>> person

But a lot of the time, the ‘keys’ are entirely ambiguous. You notice in the bracket above, we have
a string representation for the key. We can make that a variable:

var key = "name";
console.log(foo[key]);
>> person

This extends into embedded objects, as well:

var foo = {
	bar: {
		baz:"one",
		bam:"two"
	}
};
var key = "bam";
console.log(foo.bar.baz, foo.bar["baz"], foo["bar"]["baz"], foo["bar"][key]);
>>> one, one, one, two

The most “complicated” visualization of this concept you will see is using ternary operations. Consider the fact “dojo” is just an object. You often find yourself wanting to write conditional code in an if() statement only changing the core function that is called:

var toggler = function(node){
	if(dojo.hasClass(node,"thatClass")){
		dojo.removeClass(node,"thatClass");
	}else{
	 	dojo.addClass(node,"thatClass");
	}
};

Toggler above effectively toggles the class of some passed node. A shortened version of the above:

var toggler = function(node){
	var hasClass = dojo.hasClass(node,"thatClass");
	dojo[(hasClass ? "removeClass" : "addClass")](node, "thatClass");
};

The results are identical. “hasClass” is a boolean, and when true uses the first value in the block. When false it uses the second. The parameters remain the same, so we simply pass them. DRY.

The final situation I often encounter, is passing a created object hash to a function:

var prop = "height";
dojo.style(node, prop, "30px");

Because “prop” is literal, we are UNABLE to do something like:

var prop = "height";
var otherprop = "width";
// DOES NOT WORK:
dojo.style(node, {
	prop: "30px",
	otherprop: "30px"
});

Which is a bad example, but often times it is easier to maintain a single object, and pass the literal:

var horizontal = dojo.hasClass(node,"isHorizontal");
var props = {};
var prop = (horizontal ? "height" : "width");
var otherprop = (horizontal ? "width" : "height");
props[prop] = "30px";
props[otherprop] = "100%";
dojo.style(node, props);

So if our node has the class isHorizontal, the “height” value is 30px, and the “width” value is 100%. The
opposite applies with class=”isHorizontal” on the node.

Hope this helps.

Tags: ,

This entry was posted on Thursday, July 17th, 2008 at 8:09 pm and is filed under Dojo Cookies. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply

You must be logged in to post a comment.