Make your life easier - use Underscore.js
Adam Miniuk +AdamMiniuk
We talk about JavaScript. Each month in Warsaw, Poland.
Adam Miniuk +AdamMiniuk
getElementsByClassName = function(cl) {
var retnode = [];
var elem = this.getElementsByTagName('*');
for (var i = 0; i < elem.length; i++) {
if((' ' + elem[i].className + ' ').indexOf(' ' + cl + ' ') > -1) retnode.push(elem[i]);
}
return retnode;
};
As we can read on the underscorejs.org
It’s the answer to the question:
If I sit down in front of a blank HTML page, and want to start being productive immediately, what do I need?
<script src="//underscorejs.org/underscore-min.js">
</script>
<!--Then we have object called _ -->
Underscore gives us some functions to use:
each, map, reduce, reduceRight, find, filter, where,
findWhere, reject, every, some, contains, invoke,
pluck, max, min, sortBy, groupBy, indexBy, countBy,
shuffle, sample, toArray, size, partition
These are only collection functions.
var chairs = [{color: "red", width: 150},
{color: "green", width: 130}, {color: "white", width: 160}];
_.map(chairs, function(chair) {
return chair.color;
});
["red", "green", "white"]
var chairs = [{color: "red", width: 150},
{color: "green", width: 130},
{color: "green", width: 130}, {color: "white", width: 160}];
var colors = _.pluck(chairs, "color");
["red", "green", "green", "white"]
colors = _.uniq(colors);
["green", "red", "white"]
_.sortBy(colors, "length");
["red", "green", "white"]
Both approaches _.UNDERSCORE_FUNCTION(obj) and _(obj).UNDERSCORE_FUNCTION() are correct
_.sortBy(_.uniq( _.pluck(chairs, "color")), "length");
["red", "green", "white"]
_.chain(chairs)
.pluck("color")
.uniq()
.sortBy("length")
.value();
["red", "green", "white"]
There are so many functions dedicated to object. Let's just try an example.
var chair = { color: "red", width: 100 };
_.extend(chair, { color: "green" } );
{ color: "green", width: 100 }
_.defaults(chair, {color: "white", legs: 4} );
{color: "green", width: 100, legs: 4}
Many of Underscore functions have possibility to bind a context (including each).
You can use bind and bindAll to invoke particular method.
_.bind(function(name) {
return name + " chose " + this.color + " chair."
}, chair, "Adam")();
"Adam chose green chair."
var templ = _.template("<h2><%= name %> is clever.</h2>");
templ({ name: "Adam" });
<h2>Adam is clever.</h2>
<% %> executes code<%= %> prints value <%- %> prints escaped value
_.templateSettings = {
evaluate: /<\$([\s\S]+?)\$>/g,
interpolate : /{{([\s\S]+?)}}/g,
escape : /<\$-([\s\S]+?)\$>/g
};
var templ = _.template("<h2>{{ name }} is clever.</h2>");
<h2>Adam is clever.</h2>
mixin(object) with this function you can extend Underscore
_.mixin({ addDay: function (string) {
return string + " " + (new Date()).getDay();
}});
_.addDay("today's day number is");
"today's day number is 1"
random(min, max) Returns a random integer between min and max.shuffle(list) Returns a shuffled copy of the list.invert(object) Returns a copy of the object where the keys have become the values and the values the key.range([start], stop, [step]) A function to create flexibly-numbered lists of integers.pairs(object) Convert an object into a list of [key, value] pairs.isFunction(fn) instead of typeof fn === "function"has(obj, key) similiar to hasOwnProperty (falsy values safe)isEqual(object1, object2) compares two object and checks if they are identicalnoop() instead of function (){return undefined;}invoke(list, method, *arguments) calls the given method name with every element from the listdefer(fn) call the function as soon as the call stack is cleared