user1834464
user1834464

Reputation:

Why do I need to use Underscore.js _.bind method for Backbone.js custom events?

var DocumentEventsView = Backbone.View.extend({
  initialize : function () {
    $(document).on('visibilitychange', _.bind(this.onVisibilityChange, this));
  },  
  onVisibilityChange : function () {
    console.log('inside onVisibilityChange');
  }
});

So why can't I just do $(document).on('visibilitychange', 'onVisibilityChange' ?

I know the bind method is to keep and pass the context of the method, but I don't care about the context, I am never using this in onVisibilityChange. Why $(document).on('visibilitychange', 'onVisibilityChange' does not work?

Upvotes: 4

Views: 12035

Answers (3)

kol
kol

Reputation: 28698

This way the this object inside onVisibilityChange will be your view object.

If you don't need this, then don't use _.bind. The only problem is you will have to be very careful later, when you change your mind and use this inside onVisibilityChange: you will have a good chance to forget that this doesn't refer to the view object, and introduce some entertaining bugs into your code.


Here is a working example, with and without _.bind:

var  MyView1 = Backbone.View.extend({
        initialize: function () {
            $(document).on('click', _.bind(this.onClick, this));
        },
        onClick: function () {
            console.log('inside onClick, "this" is ' + this.toString());
        },
        toString: function () {
            return "[object MyView1]";
        }
    }),
    myView1 = new MyView1(),
    MyView2 = Backbone.View.extend({
        initialize: function () {
            $(document).on('dblclick', this.onDblClick);
        },
        onDblClick: function () {
            console.log('inside onDblClick, "this" is ' + this.toString());
        },
        toString: function () {
            return "[object MyView2]";
        }
    }),
    myView2 = new MyView2();

console.clear();
$(document).click();
$(document).dblclick();

Output:

inside onClick, "this" is [object MyView1]
inside onDblClick, "this" is [object HTMLDocument]

I used click and dblclick events for the sake of simplicity. Output is written to the console, press F12. Tested in latest Chrome.

Upvotes: 8

KiT O
KiT O

Reputation: 867

If you don't want to use _.bind then don't use it, and if you have problems solve it another way.

at = this;
$(document).on('visibilitychange', function(){at.onVisibilityChange();});

What _.bind do is just wrap function with another function, in that function just call original function with specified context.

Edit :

$('selector').on('event',func) calls function with context of $('selector')[0] (DOM element).

Upvotes: 0

EmptyArsenal
EmptyArsenal

Reputation: 7464

If you're using Backbone, you shouldn't bother using jQuery. Try this:

initialize: function() {
    this.on('visibilityChange', this.onVisibilityChange);
},

Upvotes: 4

Related Questions