AngularJs, Javascript

Extending underscore.js with your own methods


Every project have its own common/utilities library, many projects also use underscore.js (or even ports of this library such as underscore-java or underscore-php). You can easily integrate your own utilities functions into underscore to make thing cleaner and reduce the amount of requires (or global objects, depending where you’re holding your utilities).

In order to extend underscore with your own method you can use _.mixin .

_.mixin({
    excerpt: function(string, numOfChars) {
        return string.substr(0,numOfChars);
    }
});

Then you can easily do:

var string = _.excerpt(‘Give me first 4 chars’,4); // string = ‘Give’

That’s it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s