2013-10-22 93 views
1

我試圖讓用戶搜索集合中的displayNames和emails。Backbone Marionette Collection Filtering

到目前爲止,我的整個複合視圖看起來像下面的代碼。這呈現和記錄我的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') 
     } 
    }) 
}) 

回答

2

你可以從MarionetteCollectionViewCompositeViewview.children._views意見。

有了這樣的代碼:

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

可以隱藏意見colView有沒有條件(在你的情況條件可以是v.model.get('type') == 'todo')。

+0

編輯我的問題。 collection.where不太準確。 – azz0r

1

我認爲這可能會更容易,如果您只實例化集合的單個實例,然後調用模型上的函數。

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(); 
     } 
    } 
}); 
+0

愛這個想法,要給它一個鏡頭,謝謝 – azz0r

+0

我有上面的問題:http://jsfiddle.net/ysuMZ/1/ – azz0r

+0

不知道是什麼問題。你能提供一個小提琴嗎?我有http://jsfiddle.net/ysuMZ/2/不會拋出錯誤,但我沒有足夠的信息來運行。 – Justin