1

I hava a variable this.myvar which is a array. I would like to make a _.filter() with this variable, but within the _.filter()-function my this.myvar is not known.

is there a way to solve this, or did I comepletely misunderstood something?

this.my_array = ['aaa', 'bbb', 'ccc', 'ddd'];
this.my_filter = ['aaa', 'ccc'];

my_filtered_object = _.filter(this.my_array, function(item) {           
    alert(this.my_filter.toSource());   
    /*          
    if(this.my_filter.indexOf(item) != -1) {
                return item;
    }
    */
});

the alert should show the values of this.my_filter but it seems that there is no access within _.filter() to that variable

99Problems
  • 125
  • 2
  • 8

2 Answers2

2

There are various solutions.

  1. Store a reference in a separate variable:

    var my_filter = this.my_filter;
    my_filtered_object = _.filter(this.my_array, function(item) {           
      alert(my_filter.toSource());   
    });
    
  2. Set the context (this) inside _.filter() to point to the this outside the function:

    my_filtered_object = _.filter(this.my_array, function(item) {           
      alert(this.my_filter.toSource());   
    }, this);
    
  3. Use an arrow function expression (although this might not work in every browser):

    my_filtered_object = _.filter(this.my_array, item => {
      alert(this.my_filter.toSource());
    });
    
  4. Use _.bind(), as suggested by Mario in his answer.

Solution #2 makes most sense to me.

robertklep
  • 174,329
  • 29
  • 336
  • 330
2

The anonymous function you pass to the _.filter() need to be bind to your context if you want to access the this.my_filter.

With underscore you just need to change your code as follow:

my_filtered_object = _.filter(this.my_array, _.bind(function(item) {           
    alert(this.my_filter.toSource());   
    /*          
    if(this.my_filter.indexOf(item) != -1) {
                return item;
    }
    */
}, this));

As you can see I added the _.bind() method that attach the context you need to the anonymous function.

Mario Santini
  • 2,554
  • 2
  • 18
  • 22