Marionnette.CompositeView Filtering and emptyview

980 views
Skip to first unread message

sdne...@gmail.com

unread,
Feb 19, 2014, 3:21:45 PM2/19/14
to backbone-...@googlegroups.com
Hi,

i try to show the emptyview only if the filter is not empty and if the collection is empty  but the default behavior show it when the collection is empty.
i have tried a lot of method but it's not really easy or maybe i don't use a good method.

behaviour i try to obtain

when input filter change i fetch the collection with the new filter (server side) and if there is no result the emptyview must be show.
But if the filter is empty the emptyview must be hide.

this is my template for compositeview

<input type="search" id="query" incremental>
<div id="result">
</div>

this is the code :

var EmptyView = Marionette.ItemView.extend({
template: _.template("empty")
});
var FilterItemView = Marionette.ItemView.extend({
template : _.template("row")
}); 
    var FilterView = Marionette.CompositeView.extend({
    ui: {
    query: "#query",
    },
    events: {
         'search #query': 'search',
    },
    collectionEvents: {
    "sync": "onLoaded",
    "reset": "onLoaded"
    },
    emptyView: EmptyView,
    itemView: FilterItemView,    
    template : _.template("query"),
    itemViewContainer : "#result",
    onRender: function() {
    this.closeEmptyView();
    },
    onLoaded: function() { // collection event
    if (this.collection.length == 0) {
    if (this.ui.query.val() == "") {
    this.closeEmptyView();
    } else {
        this.showEmptyView();
        }
   
    },
    isEmpty: function() {
    if (this.collection.length == 0) {
    if (this.ui.query.val() == "") {
    return false;
    }
    return true;
    }
    return false;
    },
    search: function (e) {
    e.preventDefault();  
    if (this.ui.query.val() != "") {
     this.collection.query = this.ui.query.val();
         this.collection.fetch();
         } else {
         this.collection.reset();
         }
    }
    });


this solution works but i find it is a lot of work to do that, maybe somebody have a better method ?

Dmytro Yarmak

unread,
Mar 2, 2014, 3:42:49 AM3/2/14
to backbone-...@googlegroups.com
To override emptyView behavior you should to:
1. Override `isEmpty` method in view: https://github.com/marionettejs/backbone.marionette/blob/master/src/marionette.collectionview.js#L278-L281
2. Also when you fetch collection you should pass option `{reset: true}`. 
this.collection.fetch({reset: true});
it is necessary to trigger event `reset` on collection when fetch (even when result is empty). 
Reply all
Reply to author
Forward
0 new messages