self.el vs this.el

I'm following a backbone.js tutorial and came across 2 functions initialize() and render(). initialize() used $(self.el).append() when appending some html while render() used $(this.el).append(). I am confused about the difference, would appreciate an explaination, thanks!

JS Code

// Views
window.WineListView = Backbone.View.extend({

    tagName:'ul',

    initialize:function () {
        this.model.bind("reset", this.render, this);
        var self = this;
        this.model.bind("add", function (wine) {
            $(self.el).append(new WineListItemView({model:wine}).render().el);
        });
    },

    render:function (eventName) {
        _.each(this.model.models, function (wine) {
            $(this.el).append(new WineListItemView({model:wine}).render().el);
        }, this);
        return this;
    }
});

Answers


The first uses self to keep a reference to this when the scope changes when the event fires. Inside the anonymous function (for the event handler), this would refer to the element that fired the event rather than your Backbone controller.

The reference isn't needed in the second case.


The reason is how JavaScript handles scope.

in the initialize function they do

var self = this;

so when they bind the reference to the WineListView instance that initialized was called on

this.model.bind("add", function (wine) {
    $(self.el).append(new WineListItemView({model:wine}).render().el);
 });

But it could be done without the self variable if you send "this" as the third parameter. The third parameter should dictates scope that the callback should be called in

this.model.bind("add", function (wine) {
    $(this.el).append(new WineListItemView({model:wine}).render().el);
 }, this);

If you look at there render is bind, it also uses the third parameter

this.model.bind("reset", this.render, this);

Disclamer i havnt tried the code, but got this from reading the docs on backbone http://backbonejs.org/#FAQ-this


Need Your Help

Deleting Duplicates in Dyadic Datasets (R)

r

I have a data frame with 309,888 observations and 121 variables. I would like to delete instances where the dyad is duplicated.

Is there any way a C/C++ program can crash before main()?

c++ c function crash

Is there any way a program can crash before main()?