0

So I think that this is being passed as a way to be able to maintain the correct reference to this which should be to the View. I'm not sure though. Here is the code.

SomeView = Backbone.View.extend({

    getView: function(){
        return this.modelView;
    },
    this.collection.each(function(item){
        var ViewType = this.getModelView(item);
    }, this);
 });

So, the last this after the comma is for what? It must be to maintain reference to the correct this but I couldn't find anything that gave a good description of what it was and how it worked. Thanks for any help.

zoranc
  • 2,410
  • 1
  • 21
  • 34
David
  • 65
  • 1
  • 2
  • 8
  • That is the context parameter... `this` inside the `each()` callback will refer to the object passed as the context parameter – Arun P Johny Mar 08 '14 at 04:09
  • 1
    http://underscorejs.org/#each – dsgriffin Mar 08 '14 at 04:14
  • 1
    It's not uncommon that functions that accept a callback also accept an object which is then set as the `this` value of the callback. Most of the time the documentation usually describes whether a function does or not, like in this case. See also [How to access the correct `this` / context inside a callback?](http://stackoverflow.com/q/20279484/218196) – Felix Kling Mar 08 '14 at 04:38
  • Ok it makes sense now. Thanks Felix King. After reading through the post you linked to it makes perfect sense. – David Mar 08 '14 at 16:30

1 Answers1

-1

The context of "this" is dynamic in javascript. This mean "this" means soething different when you are in the each loop. The way around this propblem

SomeView = Backbone.View.extend({
    var self = this;
    getView: function(){
        return this.modelView;
   },
    this.collection.each(function(item){
        var ViewType = self.getModelView(item);
    }, this);
 });

you may need to place the var self = this elsewhere depending on the scope of your function

QBM5
  • 2,778
  • 2
  • 17
  • 24
  • Ok so you wouldnt need to pass "this" anymore right? It would work the same without it as long as you had the var self = this; you can just refer to that within your loop. – David Mar 08 '14 at 04:21
  • 1
    This doesn't explain why `this` is passed as second argument, which is what the question was about. The code the OP has works as expected, he wants to know *why*. – Felix Kling Mar 08 '14 at 04:36