Backbone.js Fuse.js呈现过滤集合

时间:2013-06-24 17:19:08

标签: backbone.js fuzzy-search backbone.js-collections fuse.js

我试图添加模糊搜索功能来过滤集合中的对象。控制台显示保险丝正常工作并返回正确的对象。现在的问题是如何将过滤后的集合传递给我的视图进行渲染。

这是集合:

define(["jquery", "backbone", "models/MachineModel"],

function($, Backbone, Model) {

var MachineCollection = Backbone.Collection.extend({

  model: Model,
  url: '/api/machines',
  searchablefields: ['name', 'type', 'ips', 'dataset', 'cpus', 'datacenter', 'state'], 

  rebuildIndex: function(options) {
    var _ref;
    if (options == null) {
      options = {
        keys: this.searchablefields
      };
    }
    return this._fuse = new Fuse(_.pluck(this.models, 'attributes'), options);

  },

  search: function(query) {

    this.rebuildIndex();

    var result = this._fuse.search(query);

    console.log(result);

    this.trigger('reset');

  }

});

return MachineCollection;

});

这是我的观点

define(["jquery", "backbone", "views/cloud/machines/SingleMachineView", "text!templates/cloud/machines/allMachines.html"],

function($, Backbone, SingleMachineView, template){

    var AllMachinesView = Backbone.View.extend({

        el: "#magic",

        initialize: function() {
            // Calls the view's render method
            this.collection.on('add', this.addMachine, this);
            this.collection.on('reset', this.onCollectionReset, this);
            this.render();

        },

        // View Event Handlers
        events: {
            'keyup #filter': 'fuzzySearch'
        },

        // SUBVIEWS
        // ========

        onCollectionReset: function(collection) {

            console.log('collection reset');

            var that = this;

            $(collection).each(function (model) {
                that.addMachine(model);
            });
        },

        addMachine: function(model) {

            var machineHTML = (new SingleMachineView({ model: model })).render().el;
            $(machineHTML).prependTo('#machine-container');

        },

        // FUZZY SEARCH
        // ============

        fuzzySearch: function(e) {
            var query = $(e.target).val();
            this.collection.search(query);
        },


        // RENDER
        // ======

        render: function() {

            this.template = _.template(template);

            this.$el.html(this.template);

            return this;

        }

    });

    return AllMachinesView;

 });

任何见解都会受到高度赞赏。

0 个答案:

没有答案