The default behavior of the get and set methods for an object are to return/modify the given Element attribute. Take the following for example:
var alt = document.id('myImage').get('title'); //returns the image's title attribute text
The above code modifies the title attribute for the given element. Simple, of course, but then MooTools also uses the get/set methods to set and retrieve items that aren't element attributes:var tag = document.id('myImage').get('tag'); //returns images's tag (img)
The above code retrieves the given element's tag name. How does MooTools do this? Simple: the Element.Properties object. You can set custom get and set handling by adding your desired string to the Element.Properties object. Here's an example:Element.Properties.yourCustomGetOrSetName = {
get: function() {
//your custom programming to accomplish what should be returned...
return yourReturnValue;
},
set: function(input) {
//your custom programming to accomplish what should be set...
//don't need to return anything
},
erase: function() { //erase works too!
//programming to erase this
}
};
Here's the code MooTools uses internally to accomplish the get('tag') ability:Element.Properties.tag = {
get: function(){
return this.tagName.toLowerCase();
}
};
So how could you use this? You could use Element.Properties to create a parent getter:Element.Properties.parent = {
get: function() {
return this.getParent(); //returns the element's parent
}
//no need to do a setter or eraser
};
//.....
//usage
var parent = document.id('myElement').get('parent'); //returns myElement's parent element.
Pretty sweet, no? Have any other items you'd like to see in the get or set methods? Share!