Underscore is an open source library made available by the guys at DocumentCloud.
Among all the functions provided I find very useful the following:
bind, bindAll:one of the most tricky part of Javascript is context. Sometimes you may spend hours wondering why certain fields are not accessible throughthisand the reason is the context within which the function is running. Using bind (or bindAll) you can make sure that an invocation of the functioncalculateSomethingwill be bound to a certain object and not to window when you call it like this. Note: this bind is completely different from the one coming with JQuerycalculateSomething();memoize:memoization is a technique used to cache results from frequently invoked functions. This function-object maintains an internal map having the function's invocation's input as key and the relative invocation's result as value. For example given:function isPrimaryNumber(n){...}for input 10 we will havecache[10]=false;.delay, defer,throttle,debounce:since Javascript runs in a single thread, some heavy tasks can easily freeze the browser and kill the user-experience. In order to avoid that setTimeout and setInterval are usually called to postpone sub-tasks and queue-ing them for later processing.These sets of functions make it easy to use techniques like throttling or debouncing. However, if the task to perform is quite heavy and does not impact the DOM a better alternative would be to use Web Workers instead.extend(target,sources):allows prototypal inheritance, it simply copies all the properties in sources into targetkeys,values,functions:heavily simplify reflection. These methods do not go deeper in the object's prototype hierarchy, like thefor inoperator does.wrap:allows some sort of Aspect Oriented Programming by surrounding another function's invocationisEqual:checks for equality by using === and it goes deep into the prototype's hierarchy. Keep in mind these if you are comparing large collections
Underscore encourages a functional programming approach, but if you are not familiar (yet) with it, it is still possible to opt for a more classical one by first calling
chain(), which will return a wrapper of the collection you are working on, and finally value() to get the end result.Therefore something like
_.filter(collection,function(item){return test(item);});would become
_.(collection).chain().filter(function(item){return test(item);}).value();Personally I would go directly for the functional way since Javascript provide this powerful, coincided and very expressive option to program.
Another great feature is that in case of functions like forEach, map, reduce and some others, it calls the native implementation if the version of Javascript detected supports them, in order to ensure optimum performance.
Final remark: if you decide to use backbone as your MVC framework, Underscore must be imported and all of its functions are available for all objects extending Backbone.Collection.
No comments:
Post a Comment