Last Updated: January 29, 2019
·
4.917K
· develoser

var that = this; ... An alternative with Underscore.js and _.bind()

The current frontend world is fulled of quite number of cool and useful JS Libraries like jQuery (obviously), AngularJS, MooTools, etc. and others more oriented to the architecture of your application as Backbonejs, RequireJS etc. In this case I want to talk about of one of my favorite libraries: Underscorejs (aka the "Fu" JS Library). If you come from the Backbone world you must know it ;) (if you dont you should try here http://documentcloud.github.com/underscore/)

But as the title says, this is not an introduction to this library, it's just a quick tip of the use of: _.bind(this)

So, what the hell I'm talking about? Well I'm talking about the use of some variables like self or that that are representing the this object within anonymous functions.

Take a look a the following code:

//  Class Person
function Person (name, age) {

    //  Private stuffs
    this._id = null;
    this._name = name;
    this._age = age;

    //  Getters
    this.getName = function () {
        return this._name;
    };

    this.getAge = function () {
        return this._age;
    };

    //  Setters
    this.setName = function (newName) {
        //  The name cant be empty
        if (newName == null) {
            throw 'Ilegal asignation. The name cant be null or undefined';
        } else {
            return this._name = newName;
        }
    };

    //  Is the object present in the DB?
    this.isNew = function () {
        return (this.id) ? false : true;
    };

    this.save = function () {

        //  Keep the current context
        var that = this;

        $.ajax({
            url : '/api/persons/',
            type : (this.id) ? 'PUT' : 'POST',
            data : this,
            success : function (response) {
                that._id = response.person.id;
                return that._id;
            },
            error : function () {
                throw 'Something wrong has happend :(';
            }
        });

    };

}

//  Lets create a new Person
var develoser = new Person("Jorge Luis", 26);
develoser.getName();
//  Save it!
develoser.save();

As you can see we're using the variable called that to keep a reference of the this object within the success anonymous function in the Ajax Call. In otherwise we cant use this._id within the function.

This approach works very nice, we can keep the reference of the this object and invoke its methods and properties at any time within anonymous function, but some times we want to keep our code as clean and shiny as is it posible, we dont want to use self or that or whatever you use, I want to use this the real object and not the references. So, in order to do that we can take the anonymous function and put it in the Class definition directly and calling it like success : this.puID. But not, we just want to take advantage of Underscorejs toolkit 8-) and can define anonymous functions wherever you want.

So let's take a look at the following code:

$.ajax({
    url : '/api/persons/',
    type : (this.id) ? 'PUT' : 'POST',
    data : this,
    success : function (response) {
        this._id = response.person.id;
        return this._id;
    }.bind(this),
    error : function () {
        throw 'Something wrong has happend :(';
    }
});

As you can see now we are using the this object and instead of a reference to it within the anonymous function. We can achieve it using the function _.bind(this) of Underscorejs.

And that's it.

Happy code!

1 Response
Add your response

I think you're using JavaScripts prototype.bind() here , not Underscores implementation of _.bind().

over 1 year ago ·