Search words in any order using backboneJS collection

ε祈祈猫儿з 提交于 2020-01-06 04:01:15

问题


I have code to search the typed words from the text box, Get the typed word, search it in the collection and show the result in the HTML page.

In that i can search the word exactly as it is, using LIKE.

(i.e)

search: function(type,letters){
    var pattern = new RegExp(letters,"gi");
    return _(this.filter(function(data) {
        return pattern.test(data.get(type));
    }));
}

If the model has,

  1. Hello Doctor
  2. Hi Sir
  3. Hello World
  4. Welcome Programmer

And the user types as "Hello", it shows me

Hello Doctor Hello World

I need to display the result even if the user wrongly arranges the words,

i.e If the user types as "World Hello"

It is not showing any results. But, I want to show the user

Hello World

The same scenario is solved in web SQL.
Ref here

I want to achieve this in the backboneJS collection. Can you please help me?


回答1:


You could split your text on spaces and then iteratively filter the models and reduce them to the desired selection. For example:

var C = Backbone.Collection.extend({
    search: function(type, letters) {
        var words = letters.split(/\s+/), //array of words
            models = _.clone(this.models); //copy of the models

        //for each word, check if it is found in the given attribute
        _.each(words, function(word) {
            var pattern = new RegExp(word, "i");
            models = _.filter(models, function(model) {
                return pattern.test(model.get(type));
            });
        });

        return models;
    }
});

And a demo http://jsfiddle.net/ha8RM/1/



来源:https://stackoverflow.com/questions/22321128/search-words-in-any-order-using-backbonejs-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!