New MooTools Methods: .from()

By  on  

MooTools 1.3 beta 2 was recently released and you may see a few new methods implemented to String, Array, Number, and Function: from. The from method of each of those Types returns an object of that type. Simply put: you'll always receive back an object of that type based on what you give it.

The New Method Code

Function.from = function(item){
	return (typeOf(item) == 'function') ? item : function(){
		return item;
	};
};

Array.from = function(item){
	if (item == null) return [];
	return (Type.isEnumerable(item) && typeof item != 'string') ? (typeOf(item) == 'array') ? item : Array.prototype.slice.call(item) : [item];
};

Number.from = function(item){
	var number = parseFloat(item);
	return isFinite(number) ? number : null;
};

String.from = function(item){
	return item + '';
};

The from method is added to String, Array, Number, and Function natives. Enough with the underlying code though -- examples are easier to understand.

Function.from, Array.from, Number.from, String.from Examples

Array.from('Item');
//returns ['Item'] (array type)

Function.from('Item, Whoa, Hey');
//returns function() { return 'Item, Whoa', Hey'; } (function type)

String.from(function() { alert('MooTools FTW!'); });
//returns function () { alert("MooTools FTW!"); } (string type)

Number.from('8765309');
//returns 8765309 (number type)

Each example above shows you what's returned by each method. Being able to generate a given object type from any argument using from can save you a lot of time -- especially when a given MooTools class or method requires an argument of a specific type. from is just another example of how MooTools can make your JavaScript life easier!

Recent Features

Incredible Demos

  • By
    Scrolling “Go To Top” Link Using Dojo

    One of the most popular code snippets of posted on my blog has been the scrolling "Go To Top" link snippet. The premise of the snippet is simple: once the user scrolls an element (usually the BODY element) past a given threshold, a "Go...

  • By
    Create a Photo Stack Effect with Pure CSS Animations or MooTools

    My favorite technological piece of Google Plus is its image upload and display handling.  You can drag the images from your OS right into a browser's DIV element, the images upload right before your eyes, and the albums page displays a sexy photo deck animation...

Discussion

  1. Oh great! :)

    nomore switch-cases for specific type argument…
    Life is really easier with MooTools

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