Sathya
Sathya

Reputation: 5308

BackboneJS - using keyword this inside view

If i want to call a function inside Backbone view, i have to call it like this.

this.functionName()

If i want to call the same function inside forEach Or jquery's each function, this refers to different context here. So i need to hold view's reference to some other variable and i have to use it something like below.

refresh: function () {
   var view = this;

   $("#list").each (function () {
       view.functionName();
   })
}

And finally, if i look at my view, i declare like this almost all of my functions. Did anyone find better alternative for this?

Upvotes: 0

Views: 96

Answers (3)

thibauts
thibauts

Reputation: 1648

The usuals are defining either var that = this; or var self = this; or var _this = this;

The Airbnb JavaScript Style Guide which I find very sane advocates the latter. (you may want to scroll a little to find the meat).

Upvotes: 0

Ravi Hamsa
Ravi Hamsa

Reputation: 4721

Since you are using Backbone, you would already have underscore. Using underscore you can specify context for each call.

refresh: function() {

   _.each($("#list"), function() {
      this.functionName()
   }, this))

}

Upvotes: 5

gitaarik
gitaarik

Reputation: 46290

This is indeed common in Javascript, by convention they call the variable that:

var that = this

jQuery also has a proxy() function which will call a function and set the context variable (this) to something you assign: http://api.jquery.com/jQuery.proxy/

So you could do something like this:

refresh: function() {

   $("#list").each($.proxy(function() {
       view.functionName()
   }, this))

}

But most of the times it is even more unreadable. To be honest I never use proxy() and I can't think of a good example of when to use it, but it's nice to know of it's existance, might you ever need it.

Upvotes: 1

Related Questions