【问题标题】:Backbone Marionette Collection Filtering骨干木偶集合过滤
【发布时间】:2013-10-22 14:30:44
【问题描述】:

我正在尝试允许用户搜索集合中的 displayNames 和电子邮件。

到目前为止,我的整个复合视图看起来像下面的代码。这会渲染并记录我的 var 搜索,但我不确定如何使用 collection.where 以及在新的 Backbone.Collection 之后,是否调用渲染?

define(["marionette", "text!app/templates/bamboo/employees/collection.html", "app/collections/bamboo/employees",
  "app/views/bamboo/employees/item", "jquery"],
  function(Marionette, Template, Collection, Row, $) {
    "use strict"
    return Backbone.Marionette.CompositeView.extend({
      template: Template,
      itemView: Row,
      itemViewContainer: "ul",
      collectionEvents: {
        'sync': 'hideLoading'
      },
      events: {
        'keyup #filter-input': 'initialize'
      },
      initialize: function () {
        var search = $('#filter-input').val()

        if (typeof(search) != "undefined") {
          console.log(search)
          var filtered = //somehow search collection displayName and email by value search
          this.collection = new Backbone.Collection(filtered);
        } else {
          this.showLoading()
          this.collection = new Collection()
          return this.collection.fetch()
        }
      },
      showLoading: function() {
        this.$el.addClass('loading')
      },
      hideLoading: function() {
        this.$el.removeClass('loading')
      }
  })
})

【问题讨论】:

    标签: javascript backbone.js collections marionette


    【解决方案1】:

    您可以通过view.children._views 获得来自Marionette CollectionViewCompositeView 的视图。

    使用这样的代码:

    _.each(colView.children._views,function(v){
      if(!condition){
         v.$el.hide();
      }
    });
    

    您可以隐藏colView 中没有条件的视图(在您的情况下,条件可能是v.model.get('type') == 'todo')。

    【讨论】:

    • 编辑了我的问题。 collection.where 不太准确。
    【解决方案2】:

    我认为如果您只实例化集合的单个实例,然后在模型上调用函数,这可能会更容易。

    return Backbone.Marionette.CompositeView.extend({
        template: Template,
        itemView: Row,
        itemViewContainer: "ul",
        events: {
            'keyup #filter-input': 'filter'
        },
        initialize: function() {
           this.filter();
        },
        filter: function () {
            var search = $('#filter-input').val() || '';
            this.collection.invoke('set', 'filter', search);
        },
        // ...
    });
    

    然后,对于您的 itemViews

    Row = Backbone.Marionette.ItemView.extend({
        modelEvents: {
            "change filter": "filter"
        },
        filter: function(model, search) {
            if (model.shouldBeShown(search)) {
                this.$el.show();
            } else {
                this.$el.hide();
            }
        }
    });
    

    【讨论】:

    • 不确定是什么问题。你能提供一个正在运行的小提琴吗?我有 jsfiddle.net/ysuMZ/2 不会引发错误,但我没有足够的信息让它运行。
    猜你喜欢
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2013-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-07
    相关资源
    最近更新 更多