Filter function underscore.js

I am trying to learn backbone.js and (by extension) underscore.js, and it’s hard for me to understand some of the conventions. When writing the Simpel search filter, I thought something like below would work:

var search_string = new RegExp(query, "i");

        var results = _.filter(this, function(data){
            return search_string.test(data.get("title"));
        }));

But, in fact, for this I need to change the filter function to the following:

var search_string = new RegExp(query, "i");

        var results = _(this.filter(function(data){
            return search_string.test(data.get("title"));
        }));

Basically, I want to understand why the second example works, but the first does not. Based on the documentation (http://documentcloud.github.com/underscore/#filter), I thought that the first would work. Or maybe it just reflects some old jQuery habits ... Can someone explain this to me?

+3
source share
2 answers

, Array#filter. , :

[].filter.call({ a: 'b' }, function(x) { console.log(x) });
[].filter.call([1, 2],     function(x) { console.log(x) });

, 1 2 (http://jsfiddle.net/ambiguous/tkRQ3/). , data , , native Array#filter , , .

Underscore ( filter) , :

, .

Array-ish Underscore _.m(collection, ...), , .

Backbone - , c.models, :

_.filter(this.models, function(data) { ... });

Backbone Underscore, :

- Underscore.js, 28 Backbone.Collection.

filter. Underscore , c.filter(...) _.filter(c.models, ...).

, , - " " , Underscore:

if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);

_.filter (_.filter({a:'b'}, ...)) , , _.filter(backbone_collection, ...), Underscore.

, , , : http://jsfiddle.net/ambiguous/FHd3Y/1/

+4

, $('#element') , $#element - . _ - , $ jQuery.

_() , _. _filter , _filter.

-1

All Articles