Showing posts with label Underscore. Show all posts
Showing posts with label Underscore. Show all posts

Wednesday, October 9, 2013

AngularJS with underpants

What I really meant was AngularJS with underscore but what the heck.

AngularJS as powerful as it is doesn't really have a lot utility methods and this is where underscore comes in. Underscore provides 80-odd functions that support both the usual functional suspects: map, select, invoke — as well as more specialized helpers.

To get the most of underscore with AngularJS, you have to "provide" underscore into AngularJS via a factory method:
var myapp= angular.module('underscore', []);
 myapp.factory('_', function() {
  return window._; // underscore has been loaded before this script
 }); 
With that, we can now inject underscore into our controllers:
myapp.controller("SomeCtrl",[$scope, _, function($scope, _){
    $scope.maxVal = _.max([1,2,3]); // Returns 3
});

Which leads to a couple of pretty handy stuff like checking for undefined values:
myapp.controller("SomeCtrl",[$scope, _, function($scope, _){
    if(_.isUndefined($scope.someValue){
          // do something because someValue is undefined
    }
});
Or do a search over some array using some attribute without resorting to a loop.
myapp.controller("SomeCtrl",[$scope, _, function($scope, _){
    
var data = [{model:"T", manufacturer: "Nokia"},
            {model:"S", manufacturer:"Samsung"},
            {model:"r8", manufacturer:"Cherry Mobile"},
            {model:"One", manufacturer:"HTC"}];
//Code to fetch a Cherry Mobile phone
var phone = _.where(data, {manufacturer: "Cherry Mobile"});
// phone should be [{model:"r8", manufacturer:"Cherry Mobile"}]
});
By combining these awesome frameworks, you're setting up yourself to dish out some serious can of whoop ass.

Saturday, September 8, 2012

Staring at boobs gave me an idea for Underscored Knockout

I have been using knockout.js ever since I discovered it. Since that time also, my JavaScript chops have been getting good to the point I discovered (and using) underscore.js. Let's face it, array and/or collections handling in plain JavaScript isn't pretty.

Then a couple of days ago, I was staring that this random lady's cleavage on the ride to work - had my sunglasses so she was none the wiser - that I suddenly had a great idea - Knockout's arrays with Underscore's array functionality. And I was like, "FUCK! Why did I think of this sooner?!" Needless to say, I forgot about the boobies.

When I got to work, I fired up my browser and searched the web if someone got the same idea thankfully, Kamran Ayub thought about it while driving home from work - UnderscoreKO. It's was exactly what I was thinking! If I had discovered underscore sooner, I bet I would have wrote this beauty of a library.  Now I can stop writing half-ass functions/closures of my design to merge arrays or search it for certain values and get to writing short, concise, functional Knockout code.

Thank you Kamran!