Nyxynyx
Nyxynyx

Reputation: 63727

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;
    }
});

Upvotes: 1

Views: 1329

Answers (2)

Tommyka
Tommyka

Reputation: 675

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

Upvotes: 3

Justin Niessner
Justin Niessner

Reputation: 245509

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.

Upvotes: 4

Related Questions