99Problems 99Problems - 4 months ago 7
jQuery Question

access to this.var in _.filter?

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

Answer

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.