wwli
wwli

Reputation: 2681

Backbone/javascript - confused by 'this' keyword

In the following backbone scripts, I tried to change a collection in a view click event.

var StudentView = Backbone.View.extend({

    initialize: function() {
      console.log("create  student items view");
      this.collection.bind('add',this.render,this); 
              this.collection.bind('remove',this.render,this);
    },
    render : function(){


    },
    events :{
        "click ":"select_students"
    },
    select_students: function(){
        this.collection.reset([]);
        _.each(students.models, function(m) {
            if(m.get('name')=="Daniel"){
                this.collection.add(m);
            }
        });                         
    }

});

var students_view = new  StudentView({el:$("#student_table"),collection:selected_students});    

I got this error enter image description here

How should I call "this.collection" in the code?

Upvotes: 0

Views: 649

Answers (3)

storm_m2138
storm_m2138

Reputation: 2509

Rather than using underscore's each() function, backbone collections can be iterated on directly, and can take a context to define what the 'this' variable refers to (passed as the second argument to each below).

So the best way to do this is to:

select_students: function(){
    this.collection.reset([]);
    students.each(function(m) {
        if(m.get('name')=="Daniel"){
            this.collection.add(m);
        }
    }, this);                         
}

Upvotes: 0

Steffen
Steffen

Reputation: 1

You can avoid using a reference at all, utilizing Backbone's collection filter method.

select_students: function () {
    this.collection.reset(students.filter(function (student) {
        return student.get('name') == 'Daniel';
    });
}

Upvotes: 0

go-oleg
go-oleg

Reputation: 19480

You should change you select_students to

select_students: function(){
    var self = this;
    this.collection.reset([]);
    _.each(students.models, function(m) {
        if(m.get('name')=="Daniel"){
            self.collection.add(m);
        }
    });                         
}

The problem is that in JavaScript, the this context is lost in inner functions (like the one you pass to _.each) so the general pattern is to save a reference outside of that (self) and then use that in the inner function.

Upvotes: 2

Related Questions