How does the card with the Backbone collection work?

Purpose:. I am trying to create a case insensitive search that goes through my collection and trying to match a user request with a model name attribute. Right now, if I want to find a specific model, the search query must be accurate.

There seems to be no easy way to make something so simple in Backbone, but not out of the box. The map function came to mind. What if I can go through the entire collection and change the model name attribute to lower case, and then change the user request to lower case, as well as voila!

But the problem is that I have no idea how to use the Backbone Collection and map functions. The documentation for map in the Backbone documents is missing, except for the link, which leads to the fact that you confirm the documentation with a super-primitive code example using an array of three numbers.

It doesn't work ... why?

 this.collection.map(function(model) { return model.get('name').toLowerCase(); }); 
+6
source share
1 answer

In fact, all underscore counting methods are proxied to Backbone.Collection objects. when you execute collection.map(... , it returns an array of objects returned by the displayed function. The solution provided by raina77ow does not work, because Backbone.Collection is not an array, and assigning the result of the this.collection map this.collection destroy the collection itself.

If you want to filter a collection, I would recommend using the filter method. (I assume that you are working with Backbone.View :

 var filter = this.$('#search-field').val(), filteredModels = this.collection.filter( function( model ) { return model.get('name').toLowerCase() === filter; }; this.collection.reset( filteredModels ); 

Note that any of the proxied underline methods in collections returns an array of models. If you then want to use them, you can reset the collection with these models or, equivalently, set the attribute of the collection models in the filtered results: this.collection.models = filteredModels . The first form has the advantage of triggering a reset event in a collection that you can listen to and, for example, redisplay your view.

+8
source

Source: https://habr.com/ru/post/946998/


All Articles