Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does map work with a Backbone collection?

Goal: I am trying to create a case insensitive search that goes through my collection and tries to match the user query against model's name attribute. Right now if I want to find a specific model, the search query must be exact.

It seems there is no easy way to do something so simple in Backbone, not out of the box. The function map came to mind. What if I could go through the entire collection and change model's name attribute to lower case, then change user query to lower case as well and voila!

But the problem is I have no idea how to use Backbone Collection and map function. There is no documentation on map in Backbone docs, other than a link that leads you to underscore documentation with a super primitive example code using an array of three numbers.

This does not work...why?

this.collection.map(function(model) {
  return model.get('name').toLowerCase();
});
like image 870
Sahat Yalkabov Avatar asked Jun 10 '13 23:06

Sahat Yalkabov


People also ask

How does Backbone JS work?

BackboneJS is a lightweight JavaScript library that allows to develop and structure the client side applications that run in a web browser. It offers MVC framework which abstracts data into models, DOM into views and bind these two using events.

Which of the following is the correct syntax for creating backbone collection with model model?

The Backbone. js collection models specify the array or models which are created inside of a collection. Syntax: collection.

Is backbone a MVC?

Backbone is a JavaScript MVC library and that's a key difference. In the JavaScript MVC context, a framework usually means that you need to configure your code to get things done.


1 Answers

Actually, all of underscore's collection methods are proxied on Backbone.Collection objects. when you do a collection.map(... it returns an array of objects returned by the mapped function. The solution presented by raina77ow does not work since a Backbone.Collection is not an array and assigning the result of the map to this.collection will destroy the collection itself.

If you want to filter a collection, I would recommend using the filter method. ( I assume you are working from a 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 underscore's proxied methods on collections will return an array of models. If you then want to use them, you can reset the collection with these models or, equivalently, set the collection's models attribute to the filtered results: this.collection.models = filteredModels. The first form has the advantage of triggering a reset event on the collection to which you can listen to and, for example re-render your view.

like image 71
mor Avatar answered Sep 30 '22 16:09

mor